Python type hint for specific values of dictionary

帅比萌擦擦* 提交于 2021-02-07 10:27:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!