字典特定值的 Python 类型提示 [英] Python type hint for specific values of dictionary

查看:47
本文介绍了字典特定值的 Python 类型提示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 mypy 的粉丝,我想在具有不同类型值的字典上添加一些类型提示.

I am a fan of mypy and I would like to add some type hints on a dictionary that has different type of values.

我的字典如下<代码>{'name':'John', 'age':136, 'hobbies':['Python', 'cooking', 'reading']}

目前我想到的打字是:Dict[str, Union[str, int, List[str]]

有什么办法可以指定name是一个字符串,age是一个整数,而hobbies是一个列表(为了更具体的通过 mypy) 进行类型检查?

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.

谢谢

推荐答案

我认为这可能是 XY 问题.

我的建议是为此使用一个类,而不是一个字典.这正是它们的用途.

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

这篇关于字典特定值的 Python 类型提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆