开发者

Self import of subpackages or not?

Suppose you have the following

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

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

because b/__init__.py takes care of im开发者_如何学Pythonporting 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?


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;-).


__all__ = [your vars, functions, classes]

Use syntax above in package b's __init__.py to auto load things listed in dict. :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜