[Python-ideas] Replacing the if __name__ == "__main__" idiom (was Re: making a module callable)
Guido van Rossum
guido at python.org
Sun Nov 24 20:10:43 CET 2013
Haven't followed all of this, but perhaps the simplest thing would be to
define a new builtin function that returns True in the namespace of the
main module and false everywhere else. It could be implemented by pulling
'__name__' out of the caller's local namespace and comparing it to
'__main__'. We could name this function __main__(), or perhaps less
dramatic, is_main(). Then you could write
if is_main():
<do your main code>
For people who want to use this idiom on older platforms too they can
easily implement it themselves using sys._getframe().
This is less magical than introducing a @mainfunction decorator, not really
more typing, and easily understood by people who already know the old "if
__name__ == '__main__'" idiom.
--
--Guido van Rossum (python.org/~guido)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20131124/fef81a4a/attachment.html>
More information about the Python-ideas
mailing list