What is python3's explicit type for dict_keys to check for isinstance ()?

In Python3, what type should I use to check if the dictionary keys belong to it?

>>> d = {1 : 2}
>>> type(d.keys())
<class 'dict_keys'>

      

So I tried this:

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

      

What should be placed instead of explicitly dict_keys

as the second argument for isinstance

?

(This is useful because I have to handle unknown input variables that can take the form of dictionary keys. And I know using list(d.keys())

can convert to a list (restoring Python2 behavior), but that's not an option in this case.)

+3


source to share


1 answer


You can use collections.abc.KeysView

:

In [19]: isinstance(d.keys(), collections.abc.KeysView)
Out[19]: True

      



Module

collections.abc

provides abstract base classes that can be used to check if a class provides a specific interface

+3


source







All Articles