python - 如何使用 Python 3 循环导入

标签 python python-3.x python-import circular-dependency

我想出了一个简单的代码,我无法弄清楚为什么以及如何通过循环导入来解决它。

测试.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.pytest2.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/

相关文章:

python - 根据字符串和值从嵌套列表中删除重复项

python - 导入错误 : cannot import name 'ImageTK'

python - 如何禁用 Matplotlib 中的键盘快捷键?

python - Pandas 应用一个函数将列表返回到更多列

python - 在 Python 3 中使用 for 循环查找字符串中的值

python - 如何在 pandas 中获取满足特定条件的组中的第一项?

Python "header.py"模块

django - Django Rest Framework 序列化器中的循环依赖

python : atlassian. 错误。ApiValueError : No space or no content type, 或设置了错误的版本类型设置为内容,或状态参数不是草稿

python - IEEE 754 中公式失败的概率