[Python-ideas] Import and '..', '../..' in serach path.

Ron Adam rrr at ronadam.com
Tue Jan 30 21:38:53 CET 2007


Brett Cannon wrote:
> On 1/30/07, Ron Adam <rrr at ronadam.com> wrote:
>>
>> In order to resolve a path conflict where I'm working on several 
>> copies of the
>> same package.  I found it useful to add the following near the top of 
>> modules in
>> a package or sub package.
>>
>>
>> Module in package:
>>
>>      import sys
>>      sys.path = ['..'] + sys.path
>>
>>      import package.module          # Imports module in "this!" package.
>>
>>
>> Note: There could still be conflicts if a module with the same name is 
>> in the
>> same directory as the package.  But that's much less likely than one 
>> in the rest
>> of the path.
>>
>>
>> Module in sub-package:
>>
>>      import sys
>>      sys.path = ['../..'] + sys.path
>>
>>      import package.subpackage.module   # finds "self" (subpackage) 
>> reliably.
>>
>>
>> By explicitly adding the packages parent directory to the *front* of 
>> sys.path it
>> resolves cases where imports using absolute imports, import modules 
>> from another
>> package because they are found first in the search path.
> 
> Why aren't you using relative imports (e.g., ``from . import
> module``)?  That should be doing exactly what you want.  That uses
> __path__ which is set to the path of the package.
> 
> -Brett


But if you try to run a module in a package, vs from a package, with relative
from . imports, you will get:

      ValueError: Attempted relative import in non-package

And there is no __path__ attribute to look at since no package has been imported
yet.

So you need to import the package first, and then you may not import the correct 
package even then if there is another package or module with the same name.

For example if you are running a test module from test sub-package that has a
"if __name__=='__main__': _test()" at the bottom. Something that is not
uncommon. It may attempt to import modules from a different package. In my case
it was a package with the same name in a different SVN branch. The tests
actually ran, but with errors because it wasn't exactly the same. It wasn't
obvious what was going on either.

Cheers,
Ron




More information about the Python-ideas mailing list