【问题标题】:Parametrized Union for python type annotationspython类型注释的参数化联合
【发布时间】:2020-02-03 20:32:28
【问题描述】:

我想定义一个像下面这样的泛型

MyType(OtherType) := Union[SomeClass, OtherType]

这样就不必键入以下内容来注释 x:

x: Union[SomeClass, int]

我只需要写

x: MyType[int]   # or MyType(int) for what it's worth

我必须继承Type吗?如果是这样,如何做到这一点?

【问题讨论】:

  • 如果我错了请纠正我:SomeClass 是一个固定的现有类,OtherType 是一个类型变量?
  • 没错,就是这样,如果您认为它可以使问题更清晰,请随时编辑!

标签: python python-3.x mypy python-typing


【解决方案1】:

如果我理解正确,您需要的只是TypeVar instance 之类的

from typing import TypeVar, Union


class SomeClass:
    ...


OtherType = TypeVar('OtherType')
MyType = Union[SomeClass, OtherType]


def foo(x: MyType[int]) -> int:
    return x ** 2

将这样的代码放在test.py 模块中

$ mypy test.py

给我

test.py:13: error: Unsupported operand types for ** ("SomeClass" and "int")
test.py:13: note: Left operand is of type "Union[SomeClass, int]"

并在foo中修复

def foo(x: MyType[int]) -> int:
    if isinstance(x, SomeClass):
        return 0
    return x ** 2

没有问题。

注意事项

如果我们真的需要这种类型的别名,我会这样称呼它

SomeClassOr = Union[SomeClass, OtherType]

因为

SomeClassOr[int]

对我来说似乎比

更具可读性
MyClass[int]

参考

【讨论】:

    猜你喜欢
    • 2016-11-06
    • 2020-01-28
    • 2023-03-09
    • 2018-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-14
    • 2014-09-09
    相关资源
    最近更新 更多