What is the way to check dictionary type?

Why are there many different ways to check a dictionary? And what would be the most modern way to check 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
+4
source share
2 answers

types.DictTypeand types.DictionaryTypeoutdated (well, removed in Python 3) aliases dict.

collections.Mappingand collections.MutableMappingare abstract base classes (ABC), so they work with mappings that are not a subclass of dict. This usually makes them a better choice, although occasionally a more rigorous version of typecheck may be required.

So basically check that

  • None of them, if possible (duck type)

  • collections.Mappingif you do not need a mutation

  • collections.MutableMapping,

  • dict, , dict ( )

  • types.DictType types.DictionaryType,

+10

-, types.DictType, types.DictionaryType dict ( , dict).

True , dict. , , -, .. , dict. : Mapping ( ), MutableMapping , .

+2

Source: https://habr.com/ru/post/1538154/


All Articles