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

Share:
24,546
stacksonstacks
Author by

stacksonstacks

Updated on September 25, 2020

Comments

  • stacksonstacks
    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 and typing.Mapping pretty much interchangeably.

    Is there a reason to prefer one over the other?

  • Hubert Grzeskowiak
    Hubert Grzeskowiak about 5 years
    Rule of a thumb: expect generic types, return specific types. This gives users of your functions and classes the biggest flexibility and safety.
  • Dmitry Vyal
    Dmitry Vyal over 3 years
    One more difference. Dict is invariant, Mapping is covariant. It's important when e.g. you have a function receiving Dict[A,B] and try to pass Dict[A,C] where C is a subtype of B. You will get typing error which can be avoided by using Mapping[A,B], See realpython.com/python-type-checking/….
  • Saddle Point
    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 a MutableMapping and then returns a Dict seems a bit inconvenient in this case ...