如何在 Python 中为类型定义别名以进行类型提示 [英] How to define an alias for a type in Python for type hinting

查看:46
本文介绍了如何在 Python 中为类型定义别名以进行类型提示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何为类型定义别名以使用类型提示:

How to define an alias for a type to use type hint:

import typing
type Ticker str # How to do this? I used golang notation. How do you do it in python?
Report = typing.Dict[Ticker, typing.List] 

这意味着 Ticker 是一种字符串类型,而 Report 是从 Ticker 到列表的字典.谢谢你.这种别名的好处是任何人都知道它是一个自动收报机.比写 Report = typing.Dict[str, Typing.List]

Which means Ticker is a type of string and Report is a dict from Ticker to a list. Thank you. The good thing about this aliasing is that anyone knows that it is a ticker. Much clear and more readable than writing Report = typing.Dict[str, typing.List]

推荐答案

与绑定到对象的所有其他名称一样:

As you do with all other names that you bind to objects:

Ticker = typing.Text

参见 https://docs.python.org/3/library/typing.html#type-aliases

这篇关于如何在 Python 中为类型定义别名以进行类型提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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