[Python-Dev] Magic main functions
ncoghlan at iinet.net.au
Fri Oct 15 01:27:05 CEST 2004
Phillip J. Eby wrote:
> Perhaps this means that -m is premature? I personally would rather wait
> for 2.5 if it means we get a nice, future-proof "main" convention out of
> the deal. While -m would not then be "backward compatible" with
> existing scripts, people could start changing scripts to match the
> convention as soon as there was an accepted PEP.
I see the two issues as entirely orthogonal. A new main function idiom
should not have to rely on the use of a particular command line switch
(particularly since there is no way to 'switch off' the current idiom
without significant changes to the interpreter).
If we were actually developing a new idiom, I would be thinking more
along the following lines:
"After initial execution of the __main__ module in non-interactive mode
(e.g. running a script supplied by filename or using -m), the
interpreter looks for a function also called __main__ in the __main__
module's namespace. If such a function is found, it is executed by the
interpreter as if the call __main__() had been appended to the end of
the supplied script."
Existing scripts would continue to work as is, or else could be
converted to use the new idiom by replacing the line "if __name__ ==
'__main__':" with the line "def __main__():"
Scripts that need to be backwards compatible can use the old idiom and
include the following to mark themselves as definitely being usable as
def __main__(): pass
Or else, they can be made compatible with older versions by adding the
following snippet to the end:
if __name__ == '__main__':
if sys.version_info[0:2] < [2, 5]:
About the only real practical (as opposed to aesthetic) advantage I see
to such an idiom is that the question "Is this module useful as a
script?" can easily be answered as "Yes" by looking for a __main__
function. (We can't really answer 'No' definitively, since a script may
be using the existing idiom without using the 'def __main__(): pass' trick).
Although "def __main__():" could be easier to explain to beginners than
the current approach. That might also be a slight benefit.
*stops to think for a bit*
Actually, while proofreading this, one other potential advantage occured
to me - this might allow C extensions and the like to define __main__
functions, and so be usable as scripts via -m despite their non-script
packaging. Although that seems like an awful lot of work for not much
gain - it would presumably be easier to just distribute a package that
included both the extension module and a 'launcher' Python script.
Anyway, regardless of whether a new main idiom is ever selected or not,
I just don't see the link between that and being able to search for
scripts using Python's module namespace instead of the OS filesystem's
More information about the Python-Dev