[Python-Dev] PEP 328 and PEP 338, redux

Nick Coghlan ncoghlan at iinet.net.au
Tue Jun 27 14:03:45 CEST 2006

Mitch Chapman [1] tripped over the fact that relative imports don't like main 
modules because __name__ doesn't contain any package hierarchy information.

It occurred to me that a slight modification to PEP 338 might solve the 
problem fairly cleanly: instead of simply setting __name__ to '__main__' for a 
module in a package, the -m switch could prepend the package name so that 
relative imports can work correctly.

Inside the module, the test for "am I the main module" would need to be 
"__name__.endswith('__main__')" instead of "__name__ == '__main__'", but other 
than that, there should be very little impact.

By sticking the main module into sys.modules under two different names (once 
with the package prefix and once without), runpy could even take care of 
ensuring that the following invariant held:

   import __main__
   by_name = __import__(__main__.__name__)
   assert by_name is __main__

The behaviour of top level modules would be unaffected, since they won't have 
a package prefix.


[1] http://www.python.org/sf/1510172

Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-Dev mailing list