Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python what's the best way to emulate Perl's __END__?

Tags:

python

perl

Am I correct in thinking that that Python doesn't have a direct equivalent for Perl's __END__?

print "Perl...\n";

__END__
End of code. I can put anything I want here.

One thought that occurred to me was to use a triple-quoted string. Is there a better way to achieve this in Python?

print "Python..."

"""
End of code. I can put anything I want here.
"""
like image 349
FMc Avatar asked Mar 18 '10 17:03

FMc


3 Answers

The

__END__
block in perl dates from a time when programmers had to work with data from the outside world and liked to keep examples of it in the program itself.

Hard to imagine I know.

It was useful for example if you had a moving target like a hardware log file with mutating messages due to firmware updates where you wanted to compare old and new versions of the line or keep notes not strictly related to the programs operations ("Code seems slow on day x of month every month") or as mentioned above a reference set of data to run the program against. Telcos are an example of an industry where this was a frequent requirement.

Lastly Python's cult like restrictiveness seems to have a real and tiresome effect on the mindset of its advocates, if your only response to a question is "Why would you want to that when you could do X?" when X is not as useful please keep quiet++.

like image 54
Micheal Lunny Avatar answered Nov 15 '22 05:11

Micheal Lunny


The triple-quote form you suggested will still create a python string, whereas Perl's parser simply ignores anything after __END__. You can't write:

"""
I can put anything in here...
Anything!
"""
import os
os.system("rm -rf /")

Comments are more suitable in my opinion.

#__END__
#Whatever I write here will be ignored
#Woohoo !
like image 21
Tadeusz A. Kadłubowski Avatar answered Nov 15 '22 04:11

Tadeusz A. Kadłubowski


What you're asking for does not exist. Proof: http://www.mail-archive.com/[email protected]/msg156396.html

A simple solution is to escape any " as \" and do a normal multi line string -- see official docs: http://docs.python.org/tutorial/introduction.html#strings

( Also, atexit doesn't work: http://www.mail-archive.com/[email protected]/msg156364.html )

like image 6
Simon B. Avatar answered Nov 15 '22 05:11

Simon B.