The imp module and cyclic imports

Fredrik Lundh fredrik at pythonware.com
Fri Nov 25 02:36:42 EST 2005


Matthias Kramm wrote:

> 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.

the problem you're seeing appears also if you use "import web.one"
or "from web import one" or "__import__('web.one')".

> 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

I think, but I'm not 100% sure, that the problem you're seeing is
that Python hasn't finished importing the "web.one" module when
you're trying to import it again.

    - testimport wants to import web.one
    - python imports the web module
    - python finishes importing the web module
    - python imports the web.one module
    - web.one wants to import web.two
    - python imports the web.two module
    - web.two wants to import web.one
    - python notices that web.one is already being imported, and
      leaves it to the original import to finish the task

if you replace the "from web import" statements with plain imports,
everything will work as expected.  just change

    from web import one

to

    import one

and do the same for the other module.

hope this helps!

</F>






More information about the Python-list mailing list