[Python-ideas] PEP for executing a module in a package containing relative imports (original) (raw)

Christian Heimes lists at cheimes.de
Fri Apr 20 15:43:21 CEST 2007


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.

Christian



More information about the Python-ideas mailing list