[Python-Dev] PEP 328 and PEP 338, redux
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  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.
>  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