Lỗi này là do 2 hay nhiều module import lẫn nhau nha.
Vd như mình có 2 file:
File a.py
from b import b_say_hi
def a_say_hi():
print("hi from a")
def a_say_hi_from_b():
b_say_hi()
if __name__ == '__main__':
a_say_hi_from_b()
File b.py
from a import a_say_hi
def b_say_hi():
print("hi from b")
def b_say_hi_from_a():
a_say_hi()
if __name__ == '__main__':
b_say_hi_from_a()
Khi chạy file a hay b đều có lỗi v:
> py a.py
ImportError: cannot import name 'b_say_hi' from partially initialized module 'b' (most likely due to a circular import)
> py b.py
ImportError: cannot import name 'a_say_hi' from partially initialized module 'a' (most likely due to a circular import)
Cách khắc phục là import nguyên cả module thay vì từng module nhé. :V (nguồn tham khảo)
a.py
import b
def a_say_hi():
print("hi from a")
def a_say_hi_from_b():
b.b_say_hi()
if __name__ == '__main__':
a_say_hi_from_b()
b.py
import a
def b_say_hi():
print("hi from b")
def b_say_hi_from_a():
a.a_say_hi()
if __name__ == '__main__':
b_say_hi_from_a()
> py a.py
hi from b
> py b.py
hi from a
Có đúng đâu bạn, mình có test như v:
Folder của mình
./
+-- a.py
+-- b.py
+-- sher.py
+-- numpy.py
+-- __pycache__/
+-- a.cpython-38.pyc
+-- b.cpython-38.pyc
+-- numpy.cpython-38.pyc
sher.py
import numpy as np
if __name__ == '__main__':
np.sher()
numpy.py
def sher():
print('hi from fake numpy')
> py sher.py
hi from fake numpy
Vẫn được nè.