Python type hint for specific values of dictionary

Question:

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

Asked By: Jean-Francois T.

||

Answers:

I think this might be an instance of an XY problem.

My suggestion would be to use a class for that, instead of a Dictionary. This is precisely what they are made for.

Answered By: spalac24

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"
Answered By: ggorlen
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.