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?
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.
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.
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.
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With