我在哪里可以找到dict_keys类?

时间:2016-03-03 22:25:33

标签: python python-3.x

如何直接在dict_keys课程上获得参考?目前我唯一能找到的方法是创建一个临时的dict对象并对其进行类型检查。

>>> the_class = type({}.keys())
>>> the_class
<class 'dict_keys'>
>>> the_class.__module__
'builtins'
>>> import builtins
>>> builtins.dict_keys
AttributeError: module 'builtins' has no attribute 'dict_keys'

1 个答案:

答案 0 :(得分:6)

这就是你“应该”做到这一点的方式,虽然我曾经困扰的唯一原因是在Py 2.7中修复了一个错误,其中dict_keys不是collections.KeysView的虚拟子类,我用这种技术来做Py3默认做的事情。

collections.abc(在Python中实现,而不是C)registers the type作为collections.abc.KeysView的虚拟子类时,it does

dict_keys = type({}.keys())
... many lines later ... 
KeysView.register(dict_keys)

因为在Python层没有暴露类。我认为如果Python本身没有更好的方法来完成任务,那么它可能是正确的方法。当然,你总是可以借用Python的劳动成果:

# Can't use collections.abc itself, because it only imports stuff in
# _collections_abc.__all__, and dict_keys isn't in there
from _collections_abc import dict_keys

: - )