Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check an object has the type 'dict_items'?

In Python 3, I need to test whether my variable has the type 'dict_items', so I tried something like that :

>>> d={'a':1,'b':2}
>>> d.items()
dict_items([('a', 1), ('b', 2)])
>>> isinstance(d.items(),dict_items)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'dict_items' is not defined

But dict_items is not a known type. it is not defined in types module neither. How can I test an object has the type dict_items (without consuming data) ?

like image 573
Eric Avatar asked Aug 24 '18 09:08

Eric


1 Answers

You can use collections.abc:

from collections import abc

isinstance(d.items(), abc.ItemsView)  # True

Note dict_items is a subclass of abc.ItemsView, rather than the same class. For greater precision, you can use:

isinstance(d.items(), type({}.items()))

To clarify the above, you can use issubclass:

issubclass(type(d.items()), abc.ItemsView)  # True
issubclass(abc.ItemsView, type(d.items()))  # False
like image 142
jpp Avatar answered Oct 12 '22 23:10

jpp