[Python-Dev] Magic main functions

Nick Coghlan ncoghlan at iinet.net.au
Thu Oct 14 23:06:55 CEST 2004


Barry Warsaw wrote:
> On Thu, 2004-10-14 at 10:04, Bob Ippolito wrote:
> 
> 
>>>+1.  Also, if a non-dotted module name can't be found, pyrun should be
>>>called to see if the module is actually a package (with an __main__ 
>>>that
>>>lives in the package's __init__.py).

Actually, if we were going to do something for packages, I'd be more 
inclined to look for a script called __main__.py in the package 
directory, rather than looking for a __main__ function inside 
__init__.py. Or else simply run __init__.py itself as __main__ (i.e. 
allow the use of the existing 'Python main' idiom inside a package's 
__init__.py)

(Interestingly, that's at least the second time it has been suggested to 
turn this idea into 'C-like main functions for Python'. '-m' is about 
another way to invoke the current 'if __name__ == "__main__":' idiom. It 
is most definitely *not* about creating a new idiom for main functions - 
an activity which would seem to be PEP-worthy)

>>Wouldn't it make more sense to look for main rather than __main__?  It 
>>seems that __main__ (as a function) occurs EXACTLY ZERO times in the 
>>standard library ;)
> 
> 
> I think that's a fine convention, so +1.

Except we'd be violating Python's tradition that magic methods start and 
end with double underscores, as well as potentially breaking existing 
scripts.

At the moment, the following will print 'Hello World', but with 'def 
main' being special, it would do nothing:

   def main(*args, **kwds): pass
   if __name__ == "__main__:
     print "Hello world"
     main()

I know that I often do any sys.argv manipulation in the 'if __name__' 
block rather than inside my main() function (which is often actually 
called 'main', and almost always takes a list of arguments rather than 
looking at sys.argv for itself).

So while I'd be quite happy for code that included a "def __main__" to 
break (since the Python docs advise against using names in that format), 
allowing "def main" to suddenly acquire a magic meaning may not break 
the stdlib, but I bet it would break a lot of single-purpose scripts 
that are out there.

Cheers,
Nick.


More information about the Python-Dev mailing list