[Python-Dev] PEP 338 vs PEP 328 - a limitation of the -m switch

Guido van Rossum guido at python.org
Sun Jun 18 20:18:39 CEST 2006

On 6/18/06, Nick Coghlan <ncoghlan at iinet.net.au> wrote:
> The implementations of PEP 328 (explicit relative imports) and PEP 338
> (executing modules as scripts) currently have a fight over the __name__
> attribute of a module.
> The -m switch sets __name__ to '__main__', even though it knows the module's
> real name. This is so that "if __name__ == '__main__':" blocks get executed
> properly in the main module.
> Relative imports, however, use __name__ to figure out the parent package,
> which obviously won't work if the -m switch has clobbered it.
> I think this is a solvable problem, but with beta 1 going out in a couple of
> days, I don't know if it's too late in the 2.5 cycle to fix it.
> If Anthony's willing to class this as a bug fix, it should be possible to get
> it sorted out by beta 2. I think fixing it will actually be easier than trying
> to write documentation explaining why it doesn't work right ;)
> The 'bug fix' solution would be:
>    1. Change main.c and PySys_SetPath so that '' is NOT prepended to sys.path
> when the -m switch is used
>    2. Change runpy.run_module to add a __pkg_name__ attribute if the module
> being executed is inside a package
>    3. Change import.c to check for __pkg_name__ if (and only if) __name__ ==
> '__main__' and use __pkg_name__ if it is found.

That's pretty heavy-handed for a pretty esoteric use case. (Except #1,
which I think should be done regardless as otherwise we'd get a
messed-up sys.path.)

I'd like to understand the use case better. Why can't a "script"
module inside a package use absolute imports to reference other parts
of the package?

> If we don't fix it, I'd like to document somewhere that you can't currently
> rely on relative imports if you want to be able to execute your module with
> the '-m' switch.
> However, the question I have then is. . . where? It's pretty esoteric, so I
> don't really want to put it in the tutorial, but I can't think of any other
> real documentation we have that covers how to launch the interpreter or the
> "if __name__ == '__main__':" trick.

With the docs for -m, obviously.

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

More information about the Python-Dev mailing list