[Python-Dev] PEP 328 and PEP 338, redux (original) (raw)

Guido van Rossum guido at python.org
Tue Jun 27 17:08:11 CEST 2006


On 6/27/06, Nick Coghlan <ncoghlan at iinet.net.au> wrote:

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 byname = import(main.name) assert byname is main The behaviour of top level modules would be unaffected, since they won't have a package prefix. Cheers, Nick. [1] http://www.python.org/sf/1510172

Bad idea IMO. The name == "main" rule is so ingrained, you don't want to mess with it.

Such a main module ought to use an absolute import to reach into the rest of the package.

However, I'm fine with setting another variable to the full package name so someone who really wants to do relative imports here knows the package name.

-- --Guido van Rossum (home page: http://www.python.org/~guido/)



More information about the Python-Dev mailing list