Self import of subpackages or not?

断了今生、忘了曾经 提交于 2019-12-07 02:34:57

问题


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 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?


回答1:


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




回答2:


__all__ = [your vars, functions, classes]

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



来源:https://stackoverflow.com/questions/1824001/self-import-of-subpackages-or-not

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!