Relative Imports, why the hell is it so hard?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Mar 23 16:53:57 CET 2009


En Mon, 23 Mar 2009 12:22:21 -0300, CinnamonDonkey  
<CinnamonDonkey at googlemail.com> escribió:

>>     >> \ App
>>     >> |   main.py
>>     >> +--\subpack1
>>     >> |   |   __init__.py
>>     >> |   |   module1.py
>>     >> |
>>     >> +--\subpack2
>>     >> |   |   __init__.py
>>     >> |   |   module2.py
>>
>>     >> Module1 needs to access functionality in Module2.
>>
>>     >> #module1.py
>>     >> from ..subpack2 import module2
>>
>>     >> Seems reasonable to me... but it just does not work and I was so
>>     >> liking Python. :(

Another name for relative imports is "intra-package imports". They work  
*inside* a package, and you cannot go out of the package.
If App is not a package, then subpack1 and subpack2 are separate packages  
and you cannot use relative imports between them. So module1 must refer to  
module2 absolutely:

 from subpack2 import module2

>  from ..subpack2 import module1 #ValueError: Attempted relative import
> beyond toplevel package

See the exception message.

> Max, thank you for the response... I tried adding "from __future__
> import absolute_import" which made no difference. I still get exactly
> the same error messages. Perhaps I should have mentioned that I am
> using Python 2.5, which I understand alread supports relative imports
> out of the box. I'll keep this line in for now anyway though :-)

That __future__ line is not to enable relative imports (since they have  
incompatible syntax, don't require anything special) but to ensure Python  
interprets "normal" imports (that is, without leading dots) always as  
absolute. The default behavior in 2.5 is to try *both* ways before failing.

-- 
Gabriel Genellina




More information about the Python-list mailing list