问题描述
我的团队正在与Django一起进行大型项目.为了简单起见,这里使用普通的Python来说明问题(原始问题具有模型和应用程序,而不是类(我知道它们都是类)和包(我也都知道也是包)).
My team is working on huge project with Django. For sake of simplicity, here's plain Python to illustrate the problem (original problem has models and apps instead of classes (I know that both are classes) and packages (I know that both are packages as well)).
a.py :
from b import B1
class A1(object):
def __init__(self):
print "object A1"
class A2(object):
def __init__(self):
print "object A2"
A1()
B1()
b.py :
from a import A2
class B1(object):
def __init__(self):
print "object B1"
A2()
调用 a.py 时,它将尝试从 b 包中导入 B1 ,而另一方面,该包将尝试导入< a 包中的em> A2 ,然后从头开始,这将永远重复. Python说:
When a.py is called, it tries to import B1 from b package which, on the other hand, tries to import A2 from a package and then, from start, that repeats forever. Python says:
[dagrevis@localhost recursion]$ python2 a.py
Traceback (most recent call last):
File "a.py", line 1, in <module>
from b import B1
File "/home/dagrevis/Python/recursion/b.py", line 1, in <module>
from a import A2
File "/home/dagrevis/Python/recursion/a.py", line 1, in <module>
from b import B1
ImportError: cannot import name B1
解决方案之一是每个对象只有一个文件.像C ++或Java一样.然后,我想起了Guido关于Python的说法:不要用Python编写Java(或C ++,或Javascript,...).".还有更多Python方式可以解决此问题吗?
One of the solutions would be to have one file per object. Something like C++ or Java has. Then I remembered what Guido said about Python: "Don't write Java (or C++, or Javascript, ...) in Python.". Are there more Pythonic way to deal with this problem?
谢谢您的建议!
推荐答案
您的用例不是可解决的".您可以将ImportError
转换为AttributeError
,以导入模块a
(和b
),而不是导入对象,但这不会改变您无法使用这些模块的事实.
Your use-case is not "solvable". You can turn the ImportError
into an AttributeError
importing the module a
(and b
) instead of importing the objects, but this does not change the fact that you wont be able to use these modules.
问题在于,模块a
要求在导入之前完全执行b
,而且b
要求a
在导入之前完全执行.
The problem is that your module a
requires to completely execute b
before being imported, but also b
requries a
to be completely executed before being imported.
这根本不可能解决,并且明显的症状是需要重构:您的a
和b
模块应该是一个模块(或者您可能想做一些更深层次的重构).
This is simply impossible to solve, and it's a clear symptom that a refactoring is needed: your a
and b
modules should be a single module(or you may want to do some deeper refactoring).
实际上,您也许可以解决此问题,尽管我认为这样做很丑陋,需要时将导入文件放在文件的末尾.但是我认为这只是一些更大问题的补丁.
edit:actually you may be able to solve this, even though I think it's quite ugly to do, putting the imports at the end of the file, when they are required.But I think this would be just a patch for some bigger problem.
这篇关于Python导入的无限循环;寻找Python方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!