我在哪里可以找到dict_keys类?

我在哪里可以找到dict_keys类?

问题描述:

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

>>> 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' 
+0

在Python 2中它是一个'list'。 –

+2

@PeterWood:是的,但是'dict_keys'仍然存在,实例从'dict.viewkeys'返回,其行为与Py3的'dict.keys'非常相似。 – ShadowRanger

这就是你如何“应该”做的,虽然我曾经困扰的唯一原因是修复一个bug在PY 2.7,其中dict_keys是不是collections.KeysView一个虚拟的子类,我用该技术默认做Py3。

collections.abcregisters the type(在Python,而不是C实现)作为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 

:-)