stacksonstacks
stacksonstacks

Reputation: 9313

Python type hints: typing.Mapping vs. typing.Dict

I'm working on a python3 project where we use the typing module type hints throughout.

It seems that we use typing.Dict and typing.Mapping pretty much interchangeably.

Is there a reason to prefer one over the other?

Upvotes: 142

Views: 83626

Answers (3)

stacksonstacks
stacksonstacks

Reputation: 9313

typing.Dict should be used to indicate a literal dict type with support for element type hinting i.e. Dict[bytes, str].

typing.Mapping is an object which defines the __getitem__, __len__, __iter__ magic methods.

typing.MutableMapping is an object which defines same as Mapping but with __setitem__, __delitem__ magic methods as well.

typing.Mapping et al. are based on the abc types in this table.

Upvotes: 167

Alan
Alan

Reputation: 9610

typing.Dict is deprecated since Python 3.9. Use dict instead. typing.Mapping is deprecated since Python 3.9. Use collections.abs.Mapping instead. The latter does not need to support __setitem__, __delitem__, pop, popitem, clear, update, or setdefault.

Upvotes: 3

rredondo
rredondo

Reputation: 941

As suggested by the official Python (3.11) documentation, typing.Dict is preferred for annotating return types. To annotate arguments, it is preferred to use an abstract collection type such as Mapping.

Also, typing.Dict has been deprecated since version 3.9. in favor of dict.

Upvotes: 20

Related Questions