Search code examples
pythonpython-3.xtypesordereddictionary

How to test if object has a type odict_values in Python3?


On a project I have a generic function, which can take different data types as input data. While migrating project to Python 3 I have an issue with odict_values. I need to convert those to list, unfortunately, not all data types should be converted. So I decided to do something like this:

if isinstance(data, odict_values):
    data = list(data)

But I get an error - undefined variable odict_values. I don't understand what should I provide as a second argument for isinstance. I can clearly see <class 'odict_values'> if I use type(data). The best solution I came up so far is to use:

str(type(data)) == "<class 'odict_values'>"

but it feels wrong.


Solution

  • The odict_values type is not accessible in the built-in types, nor in the collections module.

    That means you have to define it yourself:

    from collections import OrderedDict
    odict_values = type(OrderedDict().values())
    

    You can (and probably should) use a more descriptive name for this type than odict_values.

    However you can then you can use this type as second argument for isinstance checks:

    isinstance({1: 1}.values(), odict_values)                   # False
    isinstance(OrderedDict([(1, 1)]).values(), odict_values)    # True
    

    If you want a more general test if it's a view on the values of a mapping (like dict and OrderedDict), then you could use the abstract base class ValuesView:

    from collections.abc import ValuesView
    
    isinstance({1: 1}.values(), ValuesView)                   # True
    isinstance(OrderedDict([(1, 1)]).values(), ValuesView)    # True