here’s 2 py file
aa.py
import bb
b = 3
bb.foo()
bb.py
import aa
def foo():
print(aa.b)
when run from aa.py,this error came out
Traceback (most recent call last):
File "D:\pyproj\Mytest\src\aa.py", line 7, in <module>
import bb
File "D:\pyproj\Mytest\src\bb.py", line 6, in <module>
import aa
File "D:\pyproj\Mytest\src\aa.py", line 9, in <module>
bb.foo()
AttributeError: 'module' object has no attribute 'foo'
Another episode
just i want to solve the problem but i noticed something interesting or wired
i modified the test
aa.py
print('before import bb in aa.py')
import bb
print('after import bb in aa.py')
bb.foo()
print('end of all')
bb.py
def foo():
print('before import aa in bb.foo()')
import aa
print('after import aa in bb.foo()')
start from aa.py
before import bb in aa.py
after import bb in aa.py
before import aa in bb.foo()
before import bb in aa.py
after import bb in aa.py
before import aa in bb.foo()
after import aa in bb.foo()
end of all
after import aa in bb.foo()
end of all
can anyone explain this?
The problem is a circular dependency:
aaimportsbb, which importsaa. Thenaacallsbb.foo(), but this function has not yet been completely defined inbb, since the import ofaais not completed.It is better to avoid such complex dependencies. What you can do is pass
aa.bas an argument tobb.foo():aa.py
bb.py