【问题标题】:How to convert between 2 type aliases in python?如何在python中的两种类型别名之间进行转换?
【发布时间】:2021-10-17 18:48:26
【问题描述】:

我正在尝试在 python 中执行以下操作:

import typing

TypeA = str

TypeB = typing.Union[typing.List[str], typing.List[int], int, str]

TypeC = typing.Dict[str, TypeB]

def funcA(arg1: TypeC):
    var1: typing.List[TypeA] = arg1["random_key"] # static typechecker i.e. pyright is not allowing this

如何使类型检查器(即 pyright)允许此分配?

【问题讨论】:

    标签: python python-typing pyright


    【解决方案1】:

    您始终可以使用typing.cast 功能说“相信我,我知道我在做什么。”

    var1: typing.List[TypeA] = cast(typing.List[TypeA], .....)
    

    顺便说一句,如果你使用≥3.9,你可以只使用list而不是typing.List。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多