[Python-ideas] PEP for executing a module in a package containing relative imports

Brett Cannon brett at python.org
Fri Apr 20 19:15:43 CEST 2007


On 4/20/07, Christian Heimes <lists at cheimes.de> wrote:
> Brett Cannon schrieb:
> > When a module is being executed as a script, ``__main__`` will be set
> > to a true value.  For all other modules, ``__main__`` will be set to a
> > false value.  This changes the current idiom of::
> >
> >   if __name__ == '__main__':
> >       ...
> >
> > to::
> >
> >   if __main__:
> >       ...
> >
> > The current idiom is not as obvious and could cause confusion for new
> > programmers.  The proposed idiom, though, does not require explaining
> > why ``__name__`` is set as it is.
> >
> > With the proposed solution the convenience of finding out what module
> > is being executed by examining ``sys.modules['__main__']`` is lost.
> > To make up for this, the ``sys`` module will gain the ``main``
> > attribute.  It will contain a string of the name of the module that is
> > considered the executing module.
>
> What about
>
>     import sys
>     if __name__ == sys.main:
>         ...
>
> You won't have to introduce a new global module var __name__ and it's
> easy to understand for newbies and experienced developers. The code is
> only executed when the name of the current module is equal to the
> executed main module (sys.main).
> IMO it's much less PIT...B then introducing __main__.
>

True, but it does introduce an import for a module that may never be
used if the module is not being executed.  That kind of sucks for
minor performance reasons.

But what do other people think?

-Brett



More information about the Python-ideas mailing list