[英]Is this a python antipattern? 'import foo.foo as foo' shadows the rest of the foo package
Say I start off with package pack
that contains a module foo.py
. 假设我从包含模块
foo.py
软件包pack
开始。
pack/
pack/__init__.py
pack/foo.py # Defines class Foo
But for reasons, I decide I need to move foo.py
to a subpackage. 但是出于
foo.py
原因,我决定需要将foo.py
移到子包中。 Perhaps my foo is very strong and I need more functionality to manage it. 也许我的foo非常强大,我需要更多功能来对其进行管理。 Since the subpackage is all about foo, I name it
foo
as well, so now we have 由于子包全部与foo有关,因此我也将其命名为
foo
,所以现在我们有了
pack/
pack/__init__.py
pack/foo
pack/foo/__init__.py
pack/foo/foo.py # Defines class Foo
"Ah", I say, "I can make things backward compatible and avoid inflicting on calling code the excessive foo-ness of pack.foo.foo.Foo()
with the following import in pack/__init__.py
... 我说“ Ah”,“我可以使事情向后兼容,并避免在调用代码时用
pack/__init__.py
的以下import导致pack.foo.foo.Foo()
的过度pack/__init__.py
……
$ cat pack/__init__.py
import foo.foo as foo
...so that I can use pack.foo.Foo()
to initialize a Foo
." ...以便我可以使用
pack.foo.Foo()
初始化Foo
。”
Unfortunately, this means the module foo.py
shadows the rest of the foo
package, so that only the contents of pack/foo/foo.py
are visible. 不幸的是,这意味着模块
foo.py
了foo
包的其余部分,因此只有pack/foo/foo.py
的内容可见。
That's all expected behavior, my question is, would this rise to the level of an antipattern? 我的问题是,这就是所有预期的行为,这会上升到反模式的水平吗? It seems like at each step the decisions make a certain sense, so it's sort of an easy road to wander down (I have a couple of times) until all that additional functionality that motivated the subpackage says "hey what about us?"
似乎在每一步决策都具有一定意义,所以这是一条容易走的路(我有几次),直到所有激发子包的附加功能都说“嘿,我们呢?”
Is there a pythonic way to turn a module into a subpackage like this, taking into account naming and backwards compatibility? 考虑到命名和向后兼容性,是否有Python方式将模块转换为这样的子包? The
foo.foo.Foo
in particular is irksome ( datetime.datetime
notwithstanding) but maybe the answer is "just deal with it" and eat the backwards incompatibility. foo.foo.Foo
特别令人讨厌(尽管使用datetime.datetime
),但是答案可能是“只是处理它”并吃掉了向后的不兼容性。 I toyed with putting a from foo import *
somewhere, but that seems wrong. 我开玩笑地将
from foo import *
放在某个地方,但这似乎是错误的。 Or am I missing some simple solution? 还是我缺少一些简单的解决方案?
Despite my comment that the real solution is to avoid such deeply nested namespaces, I think the best approach to solving the issue once you are in it is probably to move the contents of pack/foo/foo.py
into the pack/foo/__init__.py
file. 尽管我说过真正的解决方案是避免深度嵌套的名称空间,但我认为解决该问题的最佳方法可能是将
pack/foo/foo.py
的内容移至pack/foo/__init__.py
文件。 That way you can still have other modules within the pack.foo
package, but also access the Foo
class and whatever else was in foo.py
from the same place as before ( pack.foo
). 这样,您仍然可以在
pack.foo
包中包含其他模块,而且还可以从Foo
类和foo.py
其他任何位置(与pack.foo
相同)访问其他模块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.