The imp module and cyclic imports

Matthias Kramm m.kramm at quiss.org
Thu Nov 24 15:33:34 EST 2005


Hi All,

I'm having a little bit of trouble using the "imp" module to
dynamically import modules. It seems that somehow cyclic references of
modules don't work.
I'm unable to get the following to work:

I've got the following files:

web/__init__.py
web/one.py
web/two.py
testimport.py

>From which web/one.py contains the line:

from web import two

and web/two.py contains the line:

from web import one

.

Now I try to import one of the two modules in testimport.py:

import imp
(mfile,pathname,description) = imp.find_module("one", ["web"])
m = imp.load_module("one",mfile,pathname,description)

When I start the file testimport.py, I get the following exception:

$ python testimport.py
Traceback (most recent call last):
  File "testimport.py", line 3, in ?
    m = imp.load_module("one",mfile,pathname,description)
  File "web/one.py", line 1, in ?
    from web import two
  File "/scripts/python/importtest/web/two.py", line 2, in ?
    from web import one
  File "web/one.py", line 1, in ?
    from web import two
ImportError: cannot import name two

It seems that when two.py (referenced by one.py) references one.py
again, something breaks.

I'm lost. Am I doing something wrong, or is this a bug?

Many thanks for any light anybody can shed on this.

Greetings

Matthias




More information about the Python-list mailing list