python - Python中的循环导入依赖

标签 python dependencies circular-dependency python-import

假设我有以下目录结构:

a\
    __init__.py
    b\
        __init__.py
        c\
            __init__.py
            c_file.py
        d\
            __init__.py
            d_file.py

a包的__init__.py中,引入了c包。但是 c_file.py 导入 a.b.d.

程序失败,当 c_file.py 尝试导入 a.b.d 时,说 b 不存在。 (而且它确实不存在,因为我们正在导入它。)

如何解决这个问题?

最佳答案

您可以推迟导入,例如在 a/__init__.py:

def my_function():
    from a.b.c import Blah
    return Blah()

也就是说,将导入推迟到真正需要时。但是,我也会仔细查看我的包定义/使用,因为像所指出的那样的循环依赖可能表明存在设计问题。

关于python - Python中的循环导入依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1556387/

相关文章:

python - 如何循环和访问 OpenERP 中字段的值?

python - 查找 'pip' 的模块规范时出错(AttributeError : module '__main__' has no attribute '__file__' )

c++ - 未解析的外部符号 _libvlc_new

haskell - Stack 坚持构建 Cabal 包

ruby-on-rails - Controller : Circular dependency detected while autoloading constant 中的 Rails 4 运行时错误

python - Plotly:如何组织下拉菜单?

python - 如何将 request.get 的响应转换为 DataFrame?

android - 如何在android中延迟加载共享库

c++ - 在它自己的指针上模板化一个类?

CLI 类的 C++/CLI 循环引用问题