Python type hints: typing.Mapping vs. typing.Dict
24,546
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
![stacksonstacks](https://i.stack.imgur.com/TKHBG.jpg?s=256&g=1)
Author by
stacksonstacks
Updated on September 25, 2020Comments
-
stacksonstacks almost 4 years
I'm working on a python3 project where we use the
typing
module type hints throughout.It seems that we use
typing.Dict
andtyping.Mapping
pretty much interchangeably.Is there a reason to prefer one over the other?
-
Hubert Grzeskowiak about 5 yearsRule of a thumb: expect generic types, return specific types. This gives users of your functions and classes the biggest flexibility and safety.
-
Dmitry Vyal over 3 yearsOne more difference.
Dict
is invariant,Mapping
is covariant. It's important when e.g. you have a function receivingDict[A,B]
and try to passDict[A,C]
whereC
is a subtype ofB
. You will get typing error which can be avoided by usingMapping[A,B]
, See realpython.com/python-type-checking/…. -
Saddle Point over 2 years@HubertGrzeskowiak Besides the rule, if a function preprocess on the inputs, should I use
Dict
as both input and output types? Receiving aMutableMapping
and then returns aDict
seems a bit inconvenient in this case ...