在设计较为复杂的python程序时,容易导致循环调用的问题。
显式循环调用
在python中只要两个模块相互引用了对象,那么就会构成循环调用,python解释器直接报错。即便两个模块引用的对象本身是不构成困惑的。下面举个例子
file: ps.py
from tp import print_tp
def print_ps():
print("ps")
def test_tp():
print_tp()
file: tp.py
from ps import print_ps
def print_tp():
print("tp")
def test_ps():
print_ps()
那么上述文件中不论是调用test_ps()还是test_tp()都会导致循环调用。
ImportError: cannot import name ‘print_tp’ from partially initialized module ‘tp’ (most likely due to a circular import)
隐式循环调用
模块A直接引用B的内容,而B则通过函数传参调用A的内容。这种情形下python是不会报错的。继续上边的例子:
保持file: ps.py不变,tp.py修改为如下,然后将print_ps通过参数func传入test_ps,那么python将不会报错。
file: tp.py
def print_tp():
print("tp")
def test_ps(func):
func()