Python的__init__.py文件小议(二)

之前提到了,__init__.py文件中可以导入一些包,通过 __all__开放给外部使用。
但是我为什么不领情呢?

之前用tornado,__init__.py基本都是空文件,只用来表征当前目录是一个python module。后来用flask, django 发现很多项目中都会在__init__.py 写代码。就像下面代码中注释:

因为init.py 中的这些工作,你可以通过下面的写法来使用 connect

from mongoengine import connect  # style 1

如果没有__init__.py 中的这些配置,则需要:

from mongoengine.connection import connect   # style 2

但是我更喜欢style2。
先不说让人深恶痛绝的import *, 当时我去阅读源码的时候就很纠结。
当我看到sytle1 的时候,我是懵逼的。
因为源码中mongoengine目录下并没有一个名为connect.py的文件。mongoengine目录下有一大堆py文件,我也不知道connect 方法是属于哪个py文件。

# filename: mongoengine/__init__.py
# url: https://github.com/jiaxiaolei/mongoengine/blob/master/mongoengine/__init__.py

# Import submodules so that we can expose their __all__
from mongoengine import connection
from mongoengine import document
from mongoengine import errors
from mongoengine import fields
from mongoengine import queryset
from mongoengine import signals

# Import everything from each submodule so that it can be accessed via
# mongoengine, e.g. instead of `from mongoengine.connection import connect`,
# users can simply use `from mongoengine import connect`, or even
# `from mongoengine import *` and then `connect('testdb')`.
from mongoengine.connection import *
from mongoengine.document import *
from mongoengine.errors import *
from mongoengine.fields import *
from mongoengine.queryset import *
from mongoengine.signals import *


__all__ = (list(document.__all__) + list(fields.__all__) +
           list(connection.__all__) + list(queryset.__all__) +
           list(signals.__all__) + list(errors.__all__))


VERSION = (0, 14, 0)


def get_version():
    """Return the VERSION as a string, e.g. for VERSION == (0, 10, 7),
    return '0.10.7'.
    """
    return '.'.join(map(str, VERSION))


__version__ = get_version()

你可能感兴趣的:(Python的__init__.py文件小议(二))