How about some syntactic sugar for " __name__ == '__main__' "?
steve+comp.lang.python at pearwood.info
Sat Nov 15 12:09:11 CET 2014
Chris Kaynor wrote:
> I was thinking along the lines of replacing:
> if __name__ == "__main__":
> <<<block of code>>>
> def myFunction()
> <<<<block of code>>
> Both blocks of code will be called at the same time.
You can't guarantee that, because you cannot tell ahead of time when the "if
__name__" statement will be run. It is *usually* at the end of the file,
but that's just the normal useful convention, it is not a hard requirement.
The current idiom uses normal, unmagical execution of Python code. When the
interpreter reaches the "if __name__ ..." statement, it executes that
statement, just like every other statement. There's no magic involved here,
and in fact I have written code with *multiple* such "if __name__" blocks.
Here's a sketch of the sort of thing I mean:
if __name__ == '__main__':
import c as d
def this(): ...
def that(): ...
flag = __name__ == '__main__'
if __name__ == '__main__' or condition():
print "still executing"
print "done loading"
(I haven't ever done *all* of these things in a *single* file, but I have
done all these things at one time or another.)
There's no way that any automatic system can match that for flexibility or
More information about the Python-list