python 循环导入再次(又名此设计有什么问题)
让我们考虑一下 python (3.x) 脚本:
main.py:
from test.team import team
from test.user import user
if __name__ == '__main__':
u = user()
t = team()
u.setTeam(t)
t.setLeader(u)
test/user.py:
from test.team import team
class user:
def setTeam(self, t):
if issubclass(t, team.__class__):
self.team = t
test/team.py:
from test.user import user
class team:
def setLeader(self, u):
if issubclass(u, user.__class__):
self.leader = u
现在,当然,我有了循环导入和出色的 ImportError。
所以,我不是 pythonista,我有三个问题。首先:
我。我怎样才能让这个东西发挥作用?
并且,知道有人不可避免地会说“循环导入总是表明设计问题”,第二个问题来了:
ii。为什么这个设计不好?
最后,第三个:
iii。什么是更好的选择?
准确的说,上面的类型检查只是一个例子,还有一个基于class的索引层,允许ie。找到所有用户都是一个团队的成员(用户类别有许多子类,因此对于一般用户和每个特定子类,索引加倍)或所有将用户作为成员的团队
编辑:
我希望这个更详细的例子将阐明我试图实现的目标。为了便于阅读而省略了文件(但是有一个 300kb 的源文件不知怎的让我害怕,所以请假设每个类都在不同的文件中)
# ENTITY
class Entity:
_id = None
_defs = {}
_data = None
def __init__(self, **kwargs):
self._id = uuid.uuid4() # for example. or randint(). or x+1.
self._data = {}.update(kwargs)
def __settattr__(self, name, value):
if name in self._defs:
if issubclass(value.__class__, self._defs[name]):
self._data[name] = value
# more stuff goes here, specially indexing dependencies, so we can
# do Index(some_class, name_of_property, some.object) to find all
# objects of some_class or its children where
# given property == some.object
else:
raise Exception('Some misleading message')
else:
self.__dict__[name] = value
def __gettattr__(self, name):
return self._data[name]
# USERS
class User(Entity):
_defs = {'team':Team}
class DPLUser(User):
_defs = {'team':DPLTeam}
class PythonUser(DPLUser)
pass
class PerlUser(DPLUser)
pass
class FunctionalUser(User):
_defs = {'team':FunctionalTeam}
class HaskellUser(FunctionalUser)
pass
class ErlangUser(FunctionalUser)
pass
# TEAMS
class Team(Entity):
_defs = {'leader':User}
class DPLTeam(Team):
_defs = {'leader':DPLUser}
class FunctionalTeam(Team):
_defs = {'leader':FunctionalUser}
,现在有一些用法:
t1 = FunctionalTeam()
t2 = DLPTeam()
t3 = Team()
u1 = HaskellUser()
u2 = PythonUser()
t1.leader = u1 # ok
t2.leader = u2 # ok
t1.leader = u2 # not ok, exception
t3.leader = u2 # ok
# now , index
print(Index(FunctionalTeam, 'leader', u2)) # -> [t2]
print(Index(Team, 'leader', u2)) # -> [t2,t3]
所以,它工作得很好(省略了实现细节,但没有什么复杂的)除此之外邪恶的圆形进口东西。
Let's consider python (3.x) scripts:
main.py:
from test.team import team
from test.user import user
if __name__ == '__main__':
u = user()
t = team()
u.setTeam(t)
t.setLeader(u)
test/user.py:
from test.team import team
class user:
def setTeam(self, t):
if issubclass(t, team.__class__):
self.team = t
test/team.py:
from test.user import user
class team:
def setLeader(self, u):
if issubclass(u, user.__class__):
self.leader = u
Now, of course, i've got circular import and splendid ImportError.
So, not being pythonista, I have three questions. First of all:
i. How can I make this thing work ?
And, knowing that someone will inevitably say "Circular imports always indicate a design problem", the second question comes:
ii. Why is this design bad?
And the finally, third one:
iii. What would be better alternative?
To be precise, type checking as above is only an example, there is also a index layer based on class, which permits ie. find all users being members of one team (user class has many subclasses, so index is doubled, for users in general and for each specific subclass) or all teams having given user as a member
Edit:
I hope that more detailed example will clarify what i try to achieve. Files omitted for readibility (but having one 300kb source file scares me somehow, so please assume that every class is in different file)
# ENTITY
class Entity:
_id = None
_defs = {}
_data = None
def __init__(self, **kwargs):
self._id = uuid.uuid4() # for example. or randint(). or x+1.
self._data = {}.update(kwargs)
def __settattr__(self, name, value):
if name in self._defs:
if issubclass(value.__class__, self._defs[name]):
self._data[name] = value
# more stuff goes here, specially indexing dependencies, so we can
# do Index(some_class, name_of_property, some.object) to find all
# objects of some_class or its children where
# given property == some.object
else:
raise Exception('Some misleading message')
else:
self.__dict__[name] = value
def __gettattr__(self, name):
return self._data[name]
# USERS
class User(Entity):
_defs = {'team':Team}
class DPLUser(User):
_defs = {'team':DPLTeam}
class PythonUser(DPLUser)
pass
class PerlUser(DPLUser)
pass
class FunctionalUser(User):
_defs = {'team':FunctionalTeam}
class HaskellUser(FunctionalUser)
pass
class ErlangUser(FunctionalUser)
pass
# TEAMS
class Team(Entity):
_defs = {'leader':User}
class DPLTeam(Team):
_defs = {'leader':DPLUser}
class FunctionalTeam(Team):
_defs = {'leader':FunctionalUser}
and now some usage:
t1 = FunctionalTeam()
t2 = DLPTeam()
t3 = Team()
u1 = HaskellUser()
u2 = PythonUser()
t1.leader = u1 # ok
t2.leader = u2 # ok
t1.leader = u2 # not ok, exception
t3.leader = u2 # ok
# now , index
print(Index(FunctionalTeam, 'leader', u2)) # -> [t2]
print(Index(Team, 'leader', u2)) # -> [t2,t3]
So, it works great (implementation details ommitted, but there is nothing complicated) besides of this unholy circular import thing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你可以只修复依赖图;例如,用户可能不必知道自己是团队的一部分。大多数循环依赖都允许这样的重构。
循环依赖使重构变得非常复杂,抑制了代码重用,并降低了测试中的隔离性。
尽管在 Python 中可以通过运行时导入、导入到模块级别或使用此处提到的其他技巧来规避 ImportError,但这些策略确实掩盖了设计缺陷。如果可能的话,值得避免循环导入。
You could just fix the dependency graph; for example, the user may not have to know about the fact that it is a part of a team. Most circular dependencies admit of such a refactoring.
Circular dependencies significantly complicate refactoring, inhibit code reuse, and reduce isolation in testing.
Although in Python it is possible to circumvent an
ImportError
by importing at runtime, importing to the module level, or using other tricks mentioned here, these strategies do paper over a design flaw. It is worth avoiding circular imports if at all possible.循环进口本质上并不是一件坏事。
team
代码很自然地依赖user
,而user
则与team
一起执行某些操作。这里最糟糕的做法是
from module import member
。team
模块尝试在导入时获取user
类,并且user
模块尝试获取team< /代码> 类。但
team
类尚不存在,因为当user.py
运行时,您仍位于team.py
的第一行。相反,仅导入模块。这会产生更清晰的命名空间,使以后的猴子修补成为可能,并解决了导入问题。因为您仅在导入时导入模块,所以您不必关心其中的类是否尚未定义。当你开始使用这个类时,它就会发生。
所以, test/users.py:
test/teams.py:
from test import groups
然后teams.Team
也可以,如果你想写test少。这仍然是导入模块,而不是模块成员。
另外,如果
Team
和User
相对简单,请将它们放在同一个模块中。您无需遵循 Java 每个文件一个类的习惯用法。isinstance
测试和set
方法也让我尖叫着 unpythonic-Java-wart;根据您正在做的事情,您可能最好使用普通的、未经类型检查的@property
。Circular imports are not inherently a bad thing. It's natural for the
team
code to rely onuser
whilst theuser
does something withteam
.The worse practice here is
from module import member
. Theteam
module is trying to get theuser
class at import-time, and theuser
module is trying to get theteam
class. But theteam
class doesn't exist yet because you're still at the first line ofteam.py
whenuser.py
is run.Instead, import only modules. This results in clearer namespacing, makes later monkey-patching possible, and solves the import problem. Because you're only importing the module at import-time, you don't care than the class inside it isn't defined yet. By the time you get around to using the class, it will be.
So, test/users.py:
test/teams.py:
from test import teams
and thenteams.Team
is also OK, if you want to writetest
less. That's still importing a module, not a module member.Also, if
Team
andUser
are relatively simple, put them in the same module. You don't need to follow the Java one-class-per-file idiom. Theisinstance
testing andset
methods also scream unpythonic-Java-wart to me; depending on what you're doing you may very well be better off using a plain, non-type-checked@property
.我。为了使其正常工作,您可以使用延迟导入。一种方法是保留 user.py 并将 team.py 更改为
:作为替代方案,为什么不将团队和用户类放在同一个文件中?
i. To make it work, you can use a deferred import. One way would be to leave user.py alone and change team.py to:
iii. For an alternative, why not put the team and user classes in the same file?
不好的做法/臭味如下:
my_team.leader=user_b
和user_b.team=my_team
(my_team.leader.team!=my_team) 会怎样? ?
Bad practice/smelly are the following things:
my_team.leader=user_b
anduser_b.team=my_team
(my_team.leader.team!=my_team)
?这是我还没见过的东西。直接使用 sys.modules 是一个坏主意/设计吗?阅读@bobince解决方案后,我以为我已经了解了整个导入业务,但后来遇到了一个类似于 问题 的问题,该问题链接到这个。
这是解决方案的另一种看法:
文件
test/__init__.py
文件为空。之所以有效,是因为首先导入了test.team
。当 python 导入/读取文件时,它将模块附加到 sys.modules 中。当我们导入test/user.py
时,模块test.team
已经被定义,因为我们是在main.py
中导入它的。我开始喜欢这个想法,因为模块变得非常大,但有相互依赖的函数和类。假设有一个名为 util.py 的文件,并且该文件包含许多相互依赖的类。也许我们可以将代码拆分到相互依赖的不同文件中。我们如何解决循环导入?
好吧,在 util.py 文件中,我们只需从其他“私有”文件导入所有对象,我说私有是因为这些文件不应该直接访问,而是通过原始文件访问它们file:
然后在其他每个文件上:
只要首先尝试导入
mymodule.util
,sys.modules
调用就会起作用。最后,我只会指出这样做是为了帮助用户提高可读性(较短的文件),因此我不会说循环导入“本质上”是不好的。一切都可以在同一个文件中完成,但我们使用它是为了可以分离代码,并且在滚动浏览大文件时不会感到困惑。
Here is something I haven't seen yet. Is it a bad idea/design using
sys.modules
directly? After reading @bobince solution I thought I had understood the whole importing business but then I encountered a problem similar to a question which links to this one.Here is another take on the solution:
and the file
test/__init__.py
file being empty. The reason this works is becausetest.team
is being imported first. The moment python is importing/reading a file it appends the module tosys.modules
. When we importtest/user.py
the moduletest.team
will already be defined since we are importing it inmain.py
.I'm starting to like this idea for modules that grow quite large but there are functions and classes that depend on each other. Lets suppose that there is a file called
util.py
and this file contains many classes that depend on each other. Perhaps we could split the code among different files that depend on one another. How do we get around the circular import?Well, in the
util.py
file we simply import all the objects from the other "private" files, I say private since those files are not meant to be accessed directly, instead we access them through the original file:Then on each of the other files:
The
sys.modules
call will work as long as themymodule.util
is attempted to be imported first.Lastly, I will only point out that this is being done to help users with readability (shorter files) and thus I would not say that circular imports are "inherently" bad. Everything could have been done in the same file but we are using this so that we can separate the code and not confused ourselves while scrolling through the huge file.