Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the explicit python3 type for dict_keys for isinstance() check?

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 naturally 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 I put in place of the explicit dict_keys as 2nd argument for isinstance?

(This is useful as 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 (recovering Python2 behavior) but that's not an option in this case.)

like image 316
Zhang18 Avatar asked May 11 '17 16:05

Zhang18


1 Answers

You can use 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

like image 95
Mazdak Avatar answered Oct 16 '22 00:10

Mazdak