[Python-Dev] PEP 328 and PEP 338, redux
rasky at develer.com
Thu Jun 29 14:29:26 CEST 2006
Nick Coghlan wrote:
> Writing modules that use the approach but want to work with both 2.5
> and 2.6 becomes a little more annoying - such modules have to finish
> with the coda:
> if __name__ == '__main__':
> from sys import version_info, argv
> if version_info < (2, 6):
Actually, this should be enough:
if __name__ == '__main__':
and it will still work for the "python -mpackage.module" case which we're
discussing about. The if suite can be dropped when you won't need pre-2.6
> The interpreter would also have to be careful to ensure that a
> __main__ variable in the globals isn't the result of a module doing
> "import __main__".
Real-world usage case for import __main__? Otherwise, I say screw it :)
> Another downside I've discovered recently is that calling sys.exit()
> prevents the use of a post-mortem debugging session triggered by -i
> or PYTHONINSPECT. sys.exit() crashes out of the entire process, so
> the post-mortem interactive session never even gets started.
In fact, this is an *upside* of implementing the __main__ PEP, because the
call to sys.exit() is not needed in that case. All of my Python programs
right now need a sys.exit() *because* the __main__ PEP was not implemented.
> The only real upside I can see to PEP 299 is that "main is a
> function" is more familiar to people coming from languages like C
> where you can't have run-time code at the top level of a module.
> Python's a scripting language though, and having run-time logic at
> the top level of a script is perfectly normal!
My personal argument is that if __name__ == '__main__' is totally
counter-intuitve and unpythonic. It also proves my memory: after many years,
I still have to think a couple of seconds before rememebering whether I
should use __file__, __name__ or __main__ and where to put the damn quotes.
The fact that you're comparing a variable name and a string literal which
seems very similar (both with the double underscore syntax) is totally
confusing at best.
Also, try teaching it to a beginner and he will go "huh wtf". To fully
understand it, you must understand how import exactly works (that is, the
fact that importing a module equals evaluating all of its statement one by
one). A function called __main__ which is magically invoked by the python
itself is much much easier to grasp. A different, clearer spelling for the
if condition (like: "if not __imported__") would help as well.
More information about the Python-Dev