如何在 Python 中为类型定义别名以进行类型提示

Posted

技术标签:

【中文标题】如何在 Python 中为类型定义别名以进行类型提示【英文标题】:How to define an alias for a type in Python for type hinting 【发布时间】:2018-03-23 10:01:45 【问题描述】:

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

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] 更清晰易读

【问题讨论】:

Python 中没有“五个字符的字符串”这样的类型。字符串可以是任意长度。所以你不能这样做。 好的。我把它改成了str。如何为 str 或任何其他类型定义新类型别名? Ticker = str? 【参考方案1】:

正如您对绑定到对象的所有其他名称所做的那样:

Ticker = typing.Text

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

【讨论】:

以上是关于如何在 Python 中为类型定义别名以进行类型提示的主要内容,如果未能解决你的问题,请参考以下文章