Author ncoghlan
Date 2006-06-27.11:34:45
SpamBayes Score
Marked as misclassified
Logged In: YES 

The issue isn't actually unique to the -m switch - the
problem is that relative imports are based on __name__, and
in the main module, __name__ always has the value
'__main__'. Hence, relative imports currently can't work
properly from the main module of an application, because the
main module doesn't know where it really fits in the Python
module namespace (this is at least fixable in theory for the
 main modules executed through the -m switch, but directly
executed files and the interactive interpreter are
completely out of luck).

With the old implicit relative imports this behaviour is
masked by the fact that executing a module puts that
module's directory on sys.path. When you execute a module in
a package directly, it actually imports its sibling modules
as top-level modules. The fact that the -m switch doesn't
allow this to occur is a deliberate design decision (putting
package directories on the system level path is a bad idea
because you can get multiple copies of the same module under
different names).

You should be able get something similar to the old implicit
relative import behaviour by sticking the following at the
top of your module (before doing any relative imports):

if __name__ = '__main__':
   from os.path import dirname
   __path__ = [dirname(__file__)]
   del dirname

This makes the relative import machinery treat your main
module as a package. The problem with this workaround is
that, just like the old situation with implicit relative
imports from the main module, you may end up with two
different copies of the sibling modules in sys.modules. One
copy will be '' while the other will be
'' (with implicit relative imports, the first
copy would have been a top level module called 'foo').

When I went to document this, I got stuck on the fact that
section 6 of the tutorial hasn't been updated for PEP 328 at
*all*. And the language ref palms the details off on to
Guido's packages essay. So describing the limitation in the
real documentation entails documenting PEP 328 properly in
the first place (which I'm *not* volunteering to do :).

However, I'll add a section to PEP 328 about '__main__' and
relative imports (including the workaround to get something
similar to the old behaviour back).
Date User Action Args
2007-08-23 14:40:44adminlinkissue1510172 messages
2007-08-23 14:40:44admincreate