I am a fan of mypy
and I would like to add some type hints on a dictionary that has different type of values.
My dictionary is the following
{'name':'John', 'age':136, 'hobbies':['Python', 'cooking', 'reading']}
The current typing I think of is: Dict[str, Union[str, int, List[str]]
Is there any way to specify that name
is a string, age
is an integer, and hobbies
is a list (for further specific type checking by mypy
)?
NOTE: This data is coming from an external source containing a list of such objects. I have a limited control over it, except looping through the elements and converting them.
Thanks
Since 3.8, check out TypedDict
, "a dictionary type that expects all of its instances to have a certain set of keys, where each key is associated with a value of a consistent type. This expectation is not checked at runtime but is only enforced by type checkers."
The following passes type checking:
from typing import List, TypedDict
Person = TypedDict("Person", {"name": str, "age": int, "hobbies": List[str]})
p: Person = {"name": "John", "age": 136, "hobbies": ["Python", "cooking", "reading"]}
But this doesn't:
from typing import List, TypedDict
Person = TypedDict("Person", {"name": str, "age": int, "hobbies": List[str]})
p: Person = {"name": "John", "age": 136, "hobbies": [42, "cooking", "reading"]}
Error:
main.py:4: error: List item 0 has incompatible type "int"; expected "str"