我看了一下asyncio软件包的__init__.py
文件(在Python 3.4.1中),并且在最后几行中偶然发现:
"""The asyncio package, tracking PEP 3156."""
import sys
# The selectors module is in the stdlib in Python 3.4 but not in 3.3.
# Do this first, so the other submodules can use "from . import selectors".
# Prefer asyncio/selectors.py over the stdlib one, as ours may be newer.
try:
from . import selectors
except ImportError:
import selectors # Will also be exported.
if sys.platform == 'win32':
# Similar thing for _overlapped.
try:
from . import _overlapped
except ImportError:
import _overlapped # Will also be exported.
# This relies on each of the submodules having an __all__ variable.
from .events import *
from .futures import *
from .locks import *
from .protocols import *
from .queues import *
from .streams import *
from .subprocess import *
from .tasks import *
from .transports import *
if sys.platform == 'win32': # pragma: no cover
from .windows_events import *
else:
from .unix_events import * # pragma: no cover
__all__ = (events.__all__ +
futures.__all__ +
locks.__all__ +
protocols.__all__ +
queues.__all__ +
streams.__all__ +
subprocess.__all__ +
tasks.__all__ +
transports.__all__)
考虑到上面的events
语句,当这些名称实际上根本不存在时,他们如何能够访问__all__
和所有其他子模块(及其各自的from … import *
变量) ?据我所知,标准库的asyncio/
目录不是sys.path
的一部分,子模块本身也没有定义submodule.__all__
变量。
旁注:通过查看__init__.py
文件我真正想知道的是我如何自动将所有子模块的名称添加到{{1我的包的列表__all__
而不是只重复所有这些名称(因为它是在标准库的其他几个包中完成的)。我目前的方法如下 - 也许你的答案将揭示__init__.py
包如何设法推出更具pythonic外观的技巧。
asyncio