我正在阅读 collections 模块的源代码。该模块是两个文件的组合:collections.py 和 _abcoll.py。这是 doc模块,它包含指向源代码的链接。
在collections.py的开头:
__all__ = ['Counter', 'deque', 'defaultdict', 'namedtuple', 'OrderedDict']
# For bootstrapping reasons, the collection ABCs are defined in _abcoll.py.
# They should however be considered an integral part of collections.py.
from _abcoll import *
import _abcoll
__all__ += _abcoll.__all__
...
我不太明白真正的“引导原因”是什么,因为在 _abcoll.py 中:
6 DON'T USE THIS MODULE DIRECTLY! The classes here should be imported
7 via collections; they are defined here only to alleviate certain
8 bootstrapping issues. Unit tests are in test_collections.
9 """
10
11 from abc import ABCMeta, abstractmethod
12 import sys
13
14 __all__ = ["Hashable", "Iterable", "Iterator",
15 "Sized", "Container", "Callable",
16 "Set", "MutableSet",
17 "Mapping", "MutableMapping",
18 "MappingView", "KeysView", "ItemsView", "ValuesView",
19 "Sequence", "MutableSequence",
20 ]
...
_abc.__all__
包含此文件中的所有类定义,在 collections.py 中,它从 _abcoll
导入 * 并附加 _abcoll.__all__
到它自己的 __all__
。我不明白为什么这种方式可以“缓解某些引导问题”。
有什么想法吗?谢谢
问题似乎出在旧版本的 os.py
中,例如this one :
from _abcoll import MutableMapping # Can't use collections (bootstrap)
显然,collections
间接需要 os
(可能用于模块末尾的测试,其中进行了一些酸洗,也可能在其他地方)所以会有没有 _abcoll
模块的循环依赖。
(请注意,在 Python >=3.3 中,有一个单独的 collections.abc
模块。)
我是一名优秀的程序员,十分优秀!