Python中的循环导入依赖 [英] Circular import dependency in Python

查看:196
本文介绍了Python中的循环导入依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下目录结构:

  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 import abd



程序失败,说 b 不存在 c_file.py 尝试导入 abd 。 (真的不存在,因为我们正在导入它。)



如何解决这个问题?

解决方案

如果一个依赖于c和c依赖于a,那么他们实际上是不是相同的单位吗?



你应该真正地考虑你为什么将a和c分成两个包,因为你有一些代码你应该拆分成另一个包(以使它们都依赖于这个新的包,而不是彼此),或者你应将它们合并成一个包。


Let's say I have the following directory structure:

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

In the a package's __init__.py, the c package is imported. But c_file.py imports a.b.d.

The program fails, saying b doesn't exist when c_file.py tries to import a.b.d. (And it really doesn't exist, because we were in the middle of importing it.)

How can this problem be remedied?

解决方案

If a depends on c and c depends on a, aren't they actually the same unit then?

You should really examine why you have split a and c into two packages, because either you have some code you should split off into another package (to make them both depend on that new package, but not each other), or you should merge them into one package.

这篇关于Python中的循环导入依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆