Jacques René Mesrine
Jacques René Mesrine

Reputation: 47805

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

Upvotes: 4

Views: 372

Answers (2)

nneonneo
nneonneo

Reputation: 179442

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.

Upvotes: 2

Veedrac
Veedrac

Reputation: 60147

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

Upvotes: 11

Related Questions