Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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?

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

Rule of a thumb: expect generic types, return specific types. This gives users of your functions and classes the biggest flexibility and safety. Hubert Grzeskowiak May 22, 2019 at 2:03 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/… . Dmitry Vyal Oct 9, 2020 at 9:10 @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 ... Saddle Point Feb 23, 2022 at 9:55 @HubertGrzeskowiak Hint about generic types is good.. but in this case which is more generic, Mapping or Dict? hubatish Aug 22, 2022 at 19:18 @hubatish Mapping is more generic because there are more classes than Dict that implement the 3 magic methods that Mapping stands for. DBedrenko Oct 17, 2022 at 17:43

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 .

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question . Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers .