[Python] How to check it an object is an instance of dict_itemiterator in python?

Discussão em 'Python' iniciado por Stack, Maio 29, 2025.

  1. Stack

    Stack Membro Participativo

    I have a some library that is returning dict_itemiterator object.

    Since I'm working with multiple types of objects I need to know what is actual type of my object.

    So I found that it is possible to get dict_itemiterator using this code:

    # of course, not me creating this object in real code, it comes
    # from 3rd-party library, I just added it to make a reproducible example
    my_tricky_object = iter({}.items())

    dict_itemiterator_type = type(iter({}.items()))

    if isinstance(my_tricky_object, dict_itemiterator_type):
    print('Do stuff here...')


    The problem is I don't know how to import this dict_itemiterator type without using this ambiguous construction: type(iter({}.items()))

    Of course it is possible to use Iterable:

    from typing import Iterable

    isinstance(my_tricky_object, Iterable)


    But I'm working with different iterable types and want to be sure that my_tricky_object is an instance of a specifically key/value iterator

    The question is what is most correct isinstance check here or how to import exactly dict_itemiterator type?

    Continue reading...

Compartilhe esta Página