isinstance() 检查的 dict_keys 的显式 python3 类型是什么?
What is the explicit python3 type for dict_keys for isinstance() check?
在Python3中,我应该使用什么类型来检查字典键是否属于它?
>>> d = {1 : 2}
>>> type(d.keys())
<class 'dict_keys'>
所以我很自然地尝试了这个:
>>> isinstance(d.keys(), dict_keys)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'dict_keys' is not defined
我应该用什么来代替显式 dict_keys
作为 isinstance
的第二个参数?
(这很有用,因为我必须处理可以采用字典键形式的未知输入变量。而且我知道使用 list(d.keys())
可以转换为列表(恢复 Python2 行为)但是在这种情况下,这不是一个选项。)
您可以使用 collections.abc.KeysView
:
In [19]: isinstance(d.keys(), collections.abc.KeysView)
Out[19]: True
collections.abc
module provides abstract base classes that can be
used to test whether a class provides a particular interface
使用内置类型():
isinstance(d.keys(), type({}.keys()))
在Python3中,我应该使用什么类型来检查字典键是否属于它?
>>> d = {1 : 2}
>>> type(d.keys())
<class 'dict_keys'>
所以我很自然地尝试了这个:
>>> isinstance(d.keys(), dict_keys)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'dict_keys' is not defined
我应该用什么来代替显式 dict_keys
作为 isinstance
的第二个参数?
(这很有用,因为我必须处理可以采用字典键形式的未知输入变量。而且我知道使用 list(d.keys())
可以转换为列表(恢复 Python2 行为)但是在这种情况下,这不是一个选项。)
您可以使用 collections.abc.KeysView
:
In [19]: isinstance(d.keys(), collections.abc.KeysView)
Out[19]: True
collections.abc
module provides abstract base classes that can be used to test whether a class provides a particular interface
使用内置类型():
isinstance(d.keys(), type({}.keys()))