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

Question:

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?

Asked By: stacksonstacks

||

Answers:

Managed to answer this myself.

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

Answered By: stacksonstacks

As suggested by the official python (3.11) documentation typing.Dict is useful 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.

Answered By: losaliens
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.