[Python-3000] The main module in Py3k

Nick Coghlan ncoghlan at iinet.net.au
Tue Jul 4 15:14:14 CEST 2006


PEP 299 recently got added to the list of ideas to be reconsidered for Py3k. 
The motivation seemed to be that the current idiom is both ugly and 
unintuitive if you haven't drunk enough of the relevant Koolaid.

I can't really argue with that assessment, but I think PEP 299 proposes more 
radical changes to the idiom than are really necessary.

My preferred solution would look like this:

1. Determining if the current module is the main module:

The boolean value __main__ would be defined in all modules. It would be set to 
True in the main module, and False everywhere else.

The existing "if __name__ == '__main__' idiom would be replaced by a simple 
"if __main__:"

A boolean flag that's true in the main module and false everywhere else should 
be straightforward to both teach and remember (even simpler than trying to 
explain a magic function that gets called only when the module is the main 
module).

This part of the proposal is all that most users would ever care about.


2. Accessing the main module from another module:

A new attribute in the sys module "main" would always reference the main 
module of the application. The main module would also be stored in sys.modules 
under the name "sys.main", so that "import sys.main" and "from sys import 
main" would correctly retrieve the main module.

Usages of the form "import __main__" would be replaced by "import sys.main", 
and "__main__.<attr>" would be replaced by "sys.main.<attr>".

This part of the proposal is to avoid the name conflict between "import 
__main__" and the proposed boolean flag. An alternative would be to use a 
different name for the boolean flag (e.g. invert the sense of it, and call it 
"__imported__").


3. Relative imports from the main module:

Files that are executed directly would have their __name__ attribute set to 
"<main>". Modules executed using -m would have their __name__ attribute set to 
their real module name as provided on the command line.

The main module would actually be referenced from sys.modules twice (once 
under the name "sys.main" and once under the value of sys.main.__name__)

Relative imports from directly executed modules would continue to behave as 
for the 2.x series (since the import machinery only cares about the number of 
dots preceding the module name, "<main>" will behave the same as "__main__").

Relative imports from modules executed with -m, however, would now be able to 
use the normal relative import mechanism and the __module_name__ workaround 
proposed for the 2.x series could disappear.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://www.boredomandlaziness.org


More information about the Python-3000 mailing list