10

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) ?

jpp
  • 159,742
  • 34
  • 281
  • 339
Eric
  • 4,821
  • 6
  • 33
  • 60
  • 1
    Related reading: https://stackoverflow.com/q/47273297/18771 – Tomalak Aug 24 '18 at 09:09
  • 1
    There's no way to get it directly, you could either use `type({}.items())` or use `abc.ItemsView` which basically does the [same thing internally](https://github.com/python/cpython/blob/3.7/Lib/_collections_abc.py#L53). Many other types under [`types` module](https://github.com/python/cpython/blob/3.7/Lib/types.py) are also defined in the same way. – Ashwini Chaudhary Aug 24 '18 at 09:16

2 Answers2

13

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
jpp
  • 159,742
  • 34
  • 281
  • 339
0

I prefer this approach

d={'a':1,'b':2}
d.items()

assert type(d.items()).__name__ == 'dict_items', 'Not dict_items!!!!'
assert d.items().__class__.__name__ == 'dict_items', 'Not dict_items!!!!'
NotoriousPyro
  • 526
  • 3
  • 16