[Python-Dev] Relative import bug?

Phillip J. Eby pje at telecommunity.com
Fri Sep 22 20:44:55 CEST 2006


At 08:10 PM 9/22/2006 +0200, Thomas Heller wrote:
>Consider a package containing these files:
>
>a/__init__.py
>a/b/__init__.py
>a/b/x.py
>a/b/y.py
>
>If x.py contains this:
>
>"""
>from ..b import y
>import a.b.x
>from ..b import x
>"""
>
>Python trunk and Python 2.5 both complain:
>
>Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] 
>on win32
>Type "help", "copyright", "credits" or "license" for more information.
> >>> import a.b.x
>Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "a\b\x.py", line 2, in <module>
>     from ..b import x
>ImportError: cannot import name x
> >>>
>
>A bug?

If it is, it has nothing to do with relative importing per se.  Note that 
changing it to "from a.b import x" produces the exact same error.

This looks like a "standard" circular import bug.  What's happening is that 
the first import doesn't set "a.b.x = x" until after a.b.x is fully 
imported.  But subsequent "import a.b.x" statements don't set it either, 
because they are satisfied by finding 'a.b.x' in sys.modules.  So, when the 
'from ... import x' runs, it tries to get the 'x' attribute of 'a.b' 
(whether it gets a.b relatively or absolutely), and fails.

If you make the last import be "import a.b.x as x", you'll get a better 
error message:

Traceback (most recent call last):
   File "<string>", line 1, in <module>
   File "a/b/x.py", line 3, in <module>
     import a.b.x as x
AttributeError: 'module' object has no attribute 'x'

But the entire issue is a bug that exists in Python 2.4, and possibly prior 
versions as well.



More information about the Python-Dev mailing list