我的包有以下结构:
mobilescouter/
__init__.py #1
mapper/
__init__.py #2
lxml/
__init__.py #3
vehiclemapper.py
vehiclefeaturemapper.py
vehiclefeaturesetmapper.py
...
basemapper.py
vehicle/
__init__.py #4
vehicle.py
vehiclefeature.py
vehiclefeaturemapper.py
...
我不确定__init__.py文件应该如何正确写入。__init__.py #1看起来像:
__all__ = ['mapper', 'vehicle']
import mapper
import vehicle
但是,例如__init__.py #2应该是什么样的呢?我的是:
__all__ = ['basemapper', 'lxml']
from basemaper import *
import lxml
什么时候应该使用__all__ ?
__all__非常好——它帮助引导导入语句,而不会自动导入模块
http://docs.python.org/tutorial/modules.html#importing-from-a-package
使用__all__和import *是多余的,只需要__all__
我认为在__init__.py中使用import *来导入包的最强大的原因之一是能够在不破坏现有应用程序的情况下重构已经成长为多个脚本的脚本。但如果你从一开始就在设计一个包。我认为最好将__init__.py文件保留为空。
例如:
foo.py - contains classes related to foo such as fooFactory, tallFoo, shortFoo
然后应用程序增长,现在它是一个完整的文件夹
foo/
__init__.py
foofactories.py
tallFoos.py
shortfoos.py
mediumfoos.py
santaslittlehelperfoo.py
superawsomefoo.py
anotherfoo.py
然后初始化脚本会说
__all__ = ['foofactories', 'tallFoos', 'shortfoos', 'medumfoos',
'santaslittlehelperfoo', 'superawsomefoo', 'anotherfoo']
# deprecated to keep older scripts who import this from breaking
from foo.foofactories import fooFactory
from foo.tallfoos import tallFoo
from foo.shortfoos import shortFoo
这样,执行以下操作的脚本在更改过程中就不会中断:
from foo import fooFactory, tallFoo, shortFoo
你的__init__.py应该有一个文档字符串。
Although all the functionality is implemented in modules and subpackages, your package docstring is the place to document where to start. For example, consider the python email package. The package documentation is an introduction describing the purpose, background, and how the various components within the package work together. If you automatically generate documentation from docstrings using sphinx or another package, the package docstring is exactly the right place to describe such an introduction.
其他内容请参见firecrow和Alex Martelli的精彩回答。