[Python-Dev] PEP 328 and PEP 338, redux

Nick Coghlan ncoghlan at gmail.com
Wed Jun 28 15:18:42 CEST 2006

Nick Coghlan wrote:
> Guido van Rossum wrote:
>> 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.
> OK, I'll do that. Any objections to __module_name__ as the name of the
> variable? (to keep things simple, run_module() will always define the
> variable, even if __name__ and __module_name__ say the same thing).
> I'll then put a note in PEP 338 about the necessary hackery to make relative 
> imports work correctly from a main module - I don't see any reason to include 
> something like that in the normal docs, since the recommended approach is for 
> main modules to use absolute imports.

These two bits have been done.

The workaround to replace __name__ with __module_name__ in order to enable 
relative imports turned out to be pretty ugly, so I also worked up a patch to 
import.c to get it to treat __module_name__ as an override for __name__ when 
__name__ == '__main__'.

With the patch in place, relative imports from a main module executed using 
'-m' would work out of the box.

So given a test_foo.py that started like this:

   import unittest
   import ..foo
   # Define the tests
   # Run the tests if __name__ = '__main__'

A file layout like this:


And a current working directory of /home/ncoghlan/devel, then the tests could 
be run simply by doing:

python -m package.test.test_foo

With beta 1 or current SVN, that would blow up with a ValueError.

We can't do anything to help directly executed files, though - the interpreter 
simply doesn't have access to the info it needs in order to determine the 
location of such files in the module namespace.

I'll post the patch to SF tomorrow (assuming the site decides to come back by 
then). In addition to the import.c changes, the patch includes some additional 
tests for runpy that exercise this and make sure it works, since runpy is the 
intended client.


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-Dev mailing list