2016-03-03 119 views
1

如何直接在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

回答

6

這就是你如何「應該」做的,雖然我曾經困擾的唯一原因是修復一個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 

:-)

相關問題