Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 527
stacksonstacks Avatar asked Sep 24 '18 21:09

stacksonstacks


People also ask

Is it good practice to use type hints in Python?

Type hints work best in modern Pythons. Annotations were introduced in Python 3.0, and it's possible to use type comments in Python 2.7. Still, improvements like variable annotations and postponed evaluation of type hints mean that you'll have a better experience doing type checks using Python 3.6 or even Python 3.7.

What is typing mapping in Python?

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.

Do type hints slow down Python?

So in short: no, they will not cause any run-time effects, unless you explicitly make use of them. That is incorrect. They need to be resolved when loading the code and they are kept in memory. After the loading there shouldn't be slowdowns.

What is a typed dict?

A TypedDict type represents dictionary objects with a specific set of string keys, and with specific value types for each valid key. Each string key can be either required (it must be present) or non-required (it doesn't need to exist).


1 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

like image 128
stacksonstacks Avatar answered Sep 28 '22 04:09

stacksonstacks