Relative import from script with same name as package

OKB (not okblacke) brenNOSPAMbarn at NObrenSPAMbarn.net
Sat Aug 13 19:55:38 EDT 2011


OKB (not okblacke) wrote:

>          But why?  That __future__ import is supposed to make
>          absolute 
> imports the default, so why is "import thetest" importing
> thetest.py 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 
> thetest.py 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?

    	After a bit more googling I discovered the answer here: 
http://stackoverflow.com/questions/1959188/absolute-import-failing-in-
subpackage-that-shadows-a-stdlib-package-name

    	The deal is that sys.path by default has the empty string as the 
first element, which tells Python to look first in the directory of the 
script being executed.  This is unfortunate, but can worked around this 
way:

import sys
sys.path = sys.path[1:] + ['']

(That is, move the current directory to the end of the search path 
instead of the beginning.)

-- 
--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