import A.B works, from A import B breaks

Gordon McMillan gmcm at hypernet.com
Fri Aug 4 12:27:15 EDT 2000


Oivvio Polite wrote:

>The directory 'pack' is in a directory on my python path.
>pack contains the following files
>__init__.py:
>#pack package
>__all__ = ["module1", "module2", "module3", "cmodule2", "cmodule2",
>"cmodule3"]
>
>
>module1.py:
>print "1"
>from pack import module2
>
>
>module2.py:
>print "2"
>from pack import module3
>
>
>module3.py:
>print "3"
>from pack import module1
>
>
>cmodule1.py:
>print "1"
>import pack.cmodule2
>
>
>cmodule2.py:
>print "2"
>import pack.cmodule3
>
>
>cmodule3.py:
>print "3"
>import pack.cmodule1
>
>
>Executing cmodule1.py from a shell gives this output:
>1
>2
>3
>1
>
>
>Executing module1.py from a shell gives this output:
>1
>2
>3
>1
>Traceback (innermost last):
>  File "c:/src/python/pack/module1.py", line 2, in ?
>    from pack import module2
>  File "c:\src\python\pack\module2.py", line 2, in ?
>    from pack import module3
>  File "c:\src\python\pack\module3.py", line 2, in ?
>    from pack import module1
>  File "c:\src\python\pack\module1.py", line 2, in ?
>    from pack import module2
>ImportError: cannot import name module2
>
>Could anyone explain this?

Yes.

- Gordon

Oh, OK. When cmodule3 executes "import pack.cmodule1", cmodule1 has not yet 
finished importing (it's still in the "import pack.cmodule2" statement). 
But, Python knows that it's in the process of being imported, and the name 
"pack" is bound to a valid object, so it can assume that by the time it's 
used, the name "pack.cmodule1" will be bound to a valid object.

OTOH, when module3 executes "from pack import module1", the name "module1" 
still doesn't mean anything. Since you're not going through the "pack" 
object, Python can't defer finishing the import; nor can it finish the 
import ('cause module1 is still executing "from pack import module2").



More information about the Python-list mailing list