4

我正在阅读集合模块的源代码。模块是两个文件的组合:collections.py 和 _abcoll.py。这是模块的文档,它包含指向源代码的链接。

在 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 中,它导入 * from_abcoll并附_abcoll.__all__加到它自己的__all__. 我不明白为什么这种方式可以“缓解某些引导问题”。

有什么想法吗?谢谢

4

1 回答 1

1

问题似乎出在旧版本中os.py,例如这个

from _abcoll import MutableMapping # Can't use collections (bootstrap)

显然,collections间接需要os(可能用于模块末尾的测试,其中进行了一些酸洗,也可能在其他地方进行),因此没有_abcoll模块就会存在循环依赖。

(请注意,在 Python >=3.3 中,有一个单独的collections.abc模块。)

于 2012-08-27T15:16:05.793 回答