If you run python a.py
from this directory, you get an error such as:
Traceback (most recent call last):
File "a.py", line 1, in <module>
import b
File "./b.py", line 1, in <module>
import a
File "./a.py", line 3, in <module>
b.bar()
AttributeError: 'module' object has no attribute 'bar'
I believe it runs something like this:
- Python loads module
a
and begins executing it: modulea
now exists as an object but is not yet fully defined. - The first statement in
a
isimport b
, so the runtime loads moduleb
and begins executing it. moduleb
now exists as an object but it is likewise not yet fully defined. - The first statement in
b
isimport a
, so the runtime looks for modulea
. - Runtime finds that module
a
has already been created and is in the middle of being executed, so it resumes executinga
where it left off. - Where
a
left off, is was expecting to get back the object of moduleb
. - The runtime identifies that module
b
already exists as an object, so makes it available toa
. However, it is not yet fully defined. - Thus, when module
a
attempts to execute the next line,b.bar()
, there is nobar
attribute on theb
module object, and you get the above error.
Note that if you remove the import a
from module b
, it works fine.