对于isinstance()检查,dict_keys的显式python3类型是什么?

Zha*_*g18 7 python dictionary key typechecking python-3.x

在Python3中,我应该使用什么类型来检查字典键是否属于它?

>>> d = {1 : 2}
>>> type(d.keys())
<class 'dict_keys'>
Run Code Online (Sandbox Code Playgroud)

所以很自然地我试过这个:

>>> isinstance(d.keys(), dict_keys)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'dict_keys' is not defined
Run Code Online (Sandbox Code Playgroud)

我该怎样代替明确的dict_keys第二个参数isinstance

(这很有用,因为我必须处理可以采用字典键形式的未知输入变量.我知道使用list(d.keys())可以转换为列表(恢复Python2行为)但在这种情况下这不是一个选项.)

Kas*_*mvd 7

你可以使用collections.abc.KeysView:

In [19]: isinstance(d.keys(), collections.abc.KeysView)
Out[19]: True
Run Code Online (Sandbox Code Playgroud)

collections.abc module提供了抽象基类,可用于测试类是否提供特定接口


小智 6

使用内置 type():

isinstance(d.keys(), type({}.keys()))
Run Code Online (Sandbox Code Playgroud)