Cycles between package imports

Martin Blais blais at furius.ca
Sat Jun 17 17:43:14 EDT 2006


Hi

I'm a tad confused over a problem involving cycles between
packages.

Assume the following sets of files::

  driver.py
  a/__init__.py
  a/alice.py
  b/__init__.py
  b/bob.py

Basically, two packages a and b.  Driver simply imports one of the
two.  This is the file that gets run::

,---- (driver.py)
|
| import a.alice
|
`----

The package initialization files (__init__.py) both contain
nothing.  a.alice imports b.bob, and b.bob imports a.alice.

The following works fine:

,---- (a/alice.py)
|
| import b.bob
|
`----

,---- (b/bob.py)
|
| import a.alice
|
`----


However, if I change b/bob.py to import using "from" syntax, i.e.:

,---- (b/bob.py)
|
| from a import alice
|
`----

It does not work anymore::

  Traceback (most recent call last):
    File "driver.py", line 3, in ?
      import a.alice
    File "/tmp/experiments/import-cycle/a/alice.py", line 9, in ?
      import b.bob
    File "/tmp/experiments/import-cycle/b/bob.py", line 9, in ?
      from a import alice
  ImportError: cannot import name alice


So cycles between packages do not behave as cycles between
modules--there is a subtlety.

At the time that b/bob.py attempts to import a.alice, a.alice is
still being imported (i.e. executed), and there is a difference
between

  import a.alice

and

  from a import alice


I don't see why the reference to module a.alice could not be
available via the "from" syntax, even if it is still incompletely
initialized at the time of import.

Can anyone shed some light onto this?  Is there a rule for
determining when a module becomes available to import from a
package using the "from" syntax?



More information about the Python-list mailing list