Relative import from script with same name as package

OKB (not okblacke) brenNOSPAMbarn at
Sat Aug 13 17:39:26 EDT 2011

    	I'm using Python 2.6.5.  I have a directory structure like this:

thetest/ is an empty file. contains a function foo().  
The package is accessible from sys.path, so that if I open the 
interpreter and do "import thetest" or "from thetest import thetest" or 
"import thetest.thetest", it works fine.

Inside I have code like this:

from __future__ import absolute_import

if __name__ == "__main__" and __package__ is None:
	import thetest
	__package__ = "thetest"

from .theother import foo

    	Note that I need the "import thetest" line to avoid a "parent 
module not loaded" error, as described here:

    	If I run directly, I receive a traceback like this:

Traceback (most recent call last):
  File "C:\...\thetest\", line 4, in <module>
    import thetest
  File "C:\...\thetest\", line 11, in <module>
    from .theother import foo
ValueError: Attempted relative import in non-package

    	It appears that Python is reading "import thetest" as importing (the same file that is currently being run).  When it tries 
to run that file a second time, the relative import fails.

    	But why?  That __future__ import is supposed to make absolute 
imports the default, so why is "import thetest" importing 
instead of the package called thetest?  The absolute import should make 
it look in sys.path first and not try to import from the script 
directory, right?

    	If I change the outer directory name and change the code in to match, it works fine.  But I shouldn't have to do this.  
How can I get relative imports to work correctly when running a script 
whose filename is the same as that of the directory (and thus the 
package) in which it resides?

--OKB (not okblacke)
Brendan Barnwell
"Do not follow where the path may lead.  Go, instead, where there is
no path, and leave a trail."
	--author unknown

More information about the Python-list mailing list