是否自动导入分包? [英] Self import of subpackages or not?

查看:49
本文介绍了是否自动导入分包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您具有以下

b
b/__init__.py
b/c
b/c/__init__.py
b/c/d
b/c/d/__init__.py

在某些python软件包中,如果您import b,则仅会获得b中定义的符号.要访问b.c,必须显式import b.cfrom b import c.换句话说,您必须

In some python packages, if you import b, you only get the symbols defined in b. To access b.c, you have to explicitly import b.c or from b import c. In other words, you have to

import b
import b.c
import b.c.d
print b.c.d

在其他情况下,我看到了所有子包的自动导入.这意味着以下代码不会产生错误

In other cases I saw an automatic import of all the subpackages. This means that the following code does not produce an error

import b
print b.c.d

因为b/__init__.py负责导入其子包. 我倾向于使用第一个(显式优于隐式),并且我一直使用它,但是在某些情况下第二个比第一个更受青睐吗?

because b/__init__.py takes care of importing its subpackages. I tend to prefer the first (explicit better than implicit), and I always used it, but are there cases where the second one is preferred to the first?

推荐答案

我喜欢名称空间-所以我认为import b应该只获取b本身(大概是b/__init__.py)中的内容.如果有理由将b.cb.c.d或其他功能分开,那么仅import b不应将其全部拖入-如果确实发生了全部拖入",我认为这表明命名空间分离一开始可能是虚假的.当然,即使在标准库中也有示例(import os,然后您可以使用os.path.join等),但是它们很古老,到目前为止,本质上是在Python打包系统成熟之前就祖父化"的东西.稳定.在新代码中,我强烈建议,导入时,包应拖拽其子包进行行驶. (在Python提示符下执行import this并考虑它显示的最后一行;-).

I like namespaces -- so I think that import b should only get what's in b itself (presumably in b/__init__.py). If there's a reason to segregate other functionality in b.c, b.c.d, or whatever, then just import b should not drag it all in -- if the "drag it all in" does happen, I think that suggests that the namespace separation was probably a bogus one to start with. Of course, there are examples even in the standard library (import os, then you can use os.path.join and the like), but they're ancient, by now essentially "grandfathered" things from way before the Python packaging system was mature and stable. In new code, I'd strongly recommend that a package should not drag its subpackages along for the ride when you import it. (Do import this at the Python prompt and contemplate the very last line it shows;-).

这篇关于是否自动导入分包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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