Problem with python 3.2 and circular imports
Frank Millman
frank at chagford.com
Fri Mar 4 07:22:00 EST 2011
On February 28 2011 Rafael Durán Castañeda wrote
> I'm stil totally stuck with relative imports, i' ve tried the example tree
> from PEP 328 without any result:
>
> package/
> __init__.py
> subpackage1/
> __init__.py
> moduleX.py
> moduleY.py
> subpackage2/
> __init__.py
> moduleZ.py
> moduleA.py
>
> Assuming that the current file is either moduleX.py or
> subpackage1/__init__.py, following are correct usages of the new
> syntax:
>
> from .moduleY import spam
> from .moduleY import spam as ham
> from . import moduleY
> from ..subpackage1 import moduleY
> from ..subpackage2.moduleZ import eggs
> from ..moduleA import foo
> from ...package import bar
> from ...sys import path
>
> I always get:
>
> Traceback (most recent call last):
> File "moduleY.py", line 1, in <module>
> from ..moduleA import a
> ValueError: Attempted relative import in non-package
>
>
Hi Rafael
I only just noticed your message now. For some reason it did not appear on
google.groups.
I just tried it and it worked for me. This is what I did.
I set up the above structure. I added a 'def spam()' to moduleY, 'def
eggs()' to moduleZ, and 'def foo()' to moduleA.
I pasted all of the 'from ... import ...' lines above into moduleX.
In the same directory that contains the subdirectory 'package' I create a
test script containing the following line -
import package.subpackage1.moduleX
To begin with it failed on the last two lines starting with 'from ...' [how
do you indicate three dots followed by etc etc, which would normally be
indicated by three dots!]. The traceback said 'Attempted relative import
beyond toplevel package'.
I did not want to investigate too deeply so I just commented those lines
out, and now it runs with no errors. I even put a couple of print statements
(or must I call them print functions now) into the modules being imported,
and the messages do appear, so the modules are being imported.
HTH
Frank Millman
More information about the Python-list
mailing list