Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the appropriate way to test for a dictionary type?

Why are there so many different ways to test for a dictionary? And what would be the most modern way to test if an object is a dictionary?

adict = {'a': 1}

In [10]: isinstance(adict, types.DictType)
Out[10]: True

In [11]: isinstance(adict, types.DictionaryType)
Out[11]: True

In [12]: isinstance(adict, dict)
Out[12]: True

In [13]: isinstance(adict, collections.Mapping)
Out[13]: True

In [14]: isinstance(adict, collections.MutableMapping)
Out[14]: True
like image 254
Jacques René Mesrine Avatar asked Dec 15 '22 23:12

Jacques René Mesrine


2 Answers

types.DictType and types.DictionaryType are deprecated (well, removed in Python 3) aliases of dict.

collections.Mapping and collections.MutableMapping are Abstract Base Classes (ABCs) so they work with mappings that don't subclass from dict. Normally that makes them a better choice, although very occasionally the stricter typecheck will be helpful.

So basically, check against, in order

  • None of them, if possible (duck-type)

  • collections.Mapping if you don't need mutation

  • collections.MutableMapping if you do need mutation

  • dict if you need it to actually be a dict type (this should be rare)

  • types.DictType or types.DictionaryType if you want to support really old versions

like image 138
Veedrac Avatar answered Feb 24 '23 09:02

Veedrac


First, types.DictType, types.DictionaryType, and dict are all the same (the documentation effectively notes that the first two are aliases for dict).

The last two are abstract base classes, and will actually test True for objects that don't inherit from dict at all. These are used if you want to test if an object is dict-like, i.e. whether it implements the same sort of operations that dict would. They are slightly different: Mapping is for general mappings (that may be immutable), whereas MutableMapping is strictly for mappings that can be modified.

like image 33
nneonneo Avatar answered Feb 24 '23 10:02

nneonneo