Python 上的循环导入
Circular imports on Python
嗯,我正在尝试设置 fileA
,它具有 fileB
的功能。在 file B
中,我使用了 file A
中的一些变量。是这样的:
fileA
import fileB
a = []
fileB.function1()
文件 B 是:
fileB
import fileA
def function1():
fileA.a.extend([2, 3])
但我得到这个错误:
AttributeError: module 'fileB' has no attribute 'function1'
我知道有很多关于同一件事的问题,但我还没有看到任何人有这样的错误,直到现在我找不到解决方案
在这种情况下,您可以使用本地导入而不是全局导入。我在 OpenStack 的源代码中看到了很多这样的内容。
f1.py
import f2
a = []
f2.function1()
f2.py
def function1():
import f1
f1.a.extend([2, 3])
@brunodesthuilliers how would you do avoid circular dependencies in this case?
我首先质疑为什么 f1 想要调用 f2 中的函数,而 f2 中想要访问 f1 中的变量。由于我们这里只有一个脱离任何上下文的玩具示例,因此不可能给出一个放之四海而皆准的答案,但至少有三个主要解决方案:
1. 将 f2.function 移回 f1。
如果两个人都需要如此亲密地了解对方,为什么要分开呢?
f1.py:
def function():
a.extend([2, 3, 4]])
a = []
f2.py
import f1
f1.function()
print(f1.a)
2. 将调用移至另一个模块 f3
中的 f2.function
所以 f1 不必知道 f2。
f1.py
a = []
f2.py
import f1
def function():
f1.a.extend([2, 3, 4]])
f3.py
import f1
import f2
# this is really ugly... spooky action at distance.
f2.function()
print(f1.a)
3。更改 f2.function 使其接受 a
作为参数
所以 f2 不必知道 f1
f1.py
import f2
a = []
f2.function(a)
f2.py
def function(a):
a.append([2, 3, 4])
嗯,我正在尝试设置 fileA
,它具有 fileB
的功能。在 file B
中,我使用了 file A
中的一些变量。是这样的:
fileA
import fileB
a = []
fileB.function1()
文件 B 是:
fileB
import fileA
def function1():
fileA.a.extend([2, 3])
但我得到这个错误:
AttributeError: module 'fileB' has no attribute 'function1'
我知道有很多关于同一件事的问题,但我还没有看到任何人有这样的错误,直到现在我找不到解决方案
在这种情况下,您可以使用本地导入而不是全局导入。我在 OpenStack 的源代码中看到了很多这样的内容。
f1.py
import f2
a = []
f2.function1()
f2.py
def function1():
import f1
f1.a.extend([2, 3])
@brunodesthuilliers how would you do avoid circular dependencies in this case?
我首先质疑为什么 f1 想要调用 f2 中的函数,而 f2 中想要访问 f1 中的变量。由于我们这里只有一个脱离任何上下文的玩具示例,因此不可能给出一个放之四海而皆准的答案,但至少有三个主要解决方案:
1. 将 f2.function 移回 f1。
如果两个人都需要如此亲密地了解对方,为什么要分开呢?
f1.py:
def function():
a.extend([2, 3, 4]])
a = []
f2.py
import f1
f1.function()
print(f1.a)
2. 将调用移至另一个模块 f3
中的 f2.function所以 f1 不必知道 f2。
f1.py
a = []
f2.py
import f1
def function():
f1.a.extend([2, 3, 4]])
f3.py
import f1
import f2
# this is really ugly... spooky action at distance.
f2.function()
print(f1.a)
3。更改 f2.function 使其接受 a
作为参数
所以 f2 不必知道 f1
f1.py
import f2
a = []
f2.function(a)
f2.py
def function(a):
a.append([2, 3, 4])