问题
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
回答1:
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.
来源:https://stackoverflow.com/questions/53074889/python-type-hint-for-specific-values-of-dictionary