A small module question

Guido van Rossum guido at cnri.reston.va.us
Thu Jun 10 22:31:24 CEST 1999


redhog at lysator.liu.se writes:

> I am having a problem, which is reducible to the following, which I
> would be happy if someone could explain to me:
> 
> [redhog at k35 Python]$ ls -R test/
> test:
> __init__.py  a.py  b.py
> [redhog at k35 Python]$ cat test/__init__.py
> __all__ = ["a", "b"]
> [redhog at k35 Python]$ cat test/a.py
> from test import b
> [redhog at k35 Python]$ cat test/b.py
> from test import a
> [redhog at k35 Python]$ python
> Python 1.5.1 (#1, Mar 21 1999, 22:49:36)  [GCC egcs-2.91.66 19990314/Li
> on linux-i386
> Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
> >>> from test import a
> Traceback (innermost last):
>   File "<stdin>", line 1, in ?
>   File "test/a.py", line 1, in ?
>     from test import b
>   File "test/b.py", line 1, in ?
>     from test import a
> ImportError: cannot import name a
> >>>

The "from test import a" statement ends with referencing test.a while
a isn't completely imported.  The key "test.a" exists in sys.modules,
and "import test.a" would work; however the attribute a isn't added to
the module test until after the import of a is completed.

So the solution is to use "import a" and "import b" instead -- inside
the package test, this will refer to modules test.a and test.b anyway, 
if they exist in the package.

--Guido van Rossum (home page: http://www.python.org/~guido/)




More information about the Python-list mailing list