Difference Between typing.Dict & Dict and Their Uses in Python
When declaring a dictionary as an argument in a Python function, we would generally declare the key and value data type as a global variable, not as a local one.
What if we need to declare the data type of the dictionary keys and values as a local variable? This article discusses how we can use type hints with typing.Dict
and differentiate them from the usual dict
function.
Difference Between typing.Dict
& dict
and Their Uses in Python
There is no real-world difference between using a typing.Dict
and a plain dict
when declaring a dictionary as an argument in a Python function.
However, the typing.Dict
function is a Generic type function that lets us specify the data type of the keys and values, making it more flexible.
Furthermore, since we cannot statically infer type information about objects generically kept in containers, abstract base classes have been extended to support subscriptions to denote common types for container elements.
def exampleFunction(typing.Dict[str, int])
For example, at some point in our project lifetime, we want to define the dictionary argument a little more precisely, at which point expand typing.Dict
to typing.Dict[key_type, value_type]
is a more minor change than replacing the whole dictionary with dict()
.
We can make our dictionaries more generic by using the Mapping
or MutableMapping
types. A dictionary is one mapping, but we could create other objects that satisfy the mapping interface.
def exampleFunction(typing.Mapping[str, int])
Note that Python doesn’t enforce type hints. They are just hints and are not used to implement types at runtime or compile time.
However, if we use Python version 3.9 and above, Python has deprecated typing.Dict
and instead enforced type hints in the built-in dict()
commands. We can specify the type while declaring a dictionary in Python.
def exampleFunction(dict[str, int])
Marion specializes in anything Microsoft-related and always tries to work and apply code in an IT infrastructure.
LinkedIn