[Python-Dev] PEP 338 vs PEP 328 - a limitation of the -m switch
ncoghlan at iinet.net.au
Sun Jun 18 16:42:08 CEST 2006
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.
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.
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
More information about the Python-Dev