【问题标题】:How to define an alias for a type in Python for type hinting如何在 Python 中为类型定义别名以进行类型提示
【发布时间】: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?

标签: python type-hinting typing


【解决方案1】:

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

Ticker = typing.Text

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

【讨论】:

    猜你喜欢
    • 2022-08-18
    • 2020-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-04
    • 2019-05-19
    • 2022-08-04
    相关资源
    最近更新 更多