我想出了一个简单的代码,我无法弄清楚为什么以及如何通过循环导入来解决它。
测试.py
from test2 import specific_ID
store_name = "testing"
STORE_ID = specific_ID()
print(STORE_ID)
test2.py
from test import store_name
print(store_name)
def specific_ID():
print("Yay works")
print(f"Store name: {store_name}")
return True
我的想法是,当我在 test.py
中有变量 store_name
时,我希望它是一种“常量”值,我可以在其中重新使用 test2.py
中的值 - 但是它似乎不喜欢它抛出错误的地方:
from test2 import specific_ID
ImportError: cannot import name 'specific_ID' from partially initialized module 'test2' (most likely due to a circular import)
我的问题是,如何将一个变量从 test.py 重用到 test.py?
最佳答案
应该避免循环导入,只需将 test.py 和 test2.py 放在一个包中,并将它们的共享全局变量放在主命名空间中:
__init__.py
STORE_NAME = 'testing'
test.py 和 test2.py
from . import STORE_NAME
但是你可以一起规避全局变量:
test2.py
def specific_ID(store_name: str) -> int:
"Return the ID for a store"
print("Yay works")
print(f"Store name: {store_name}")
# lookup id
return id
测试.py
from test2 import specific_ID
store_name = "testing"
STORE_ID = specific_ID(store_name)
print(STORE_ID)
当你的函数是纯函数,与全局状态分离时,这使得它们更容易推理和重构。
关于python - 如何使用 Python 3 循环导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68773791/