繁体   English   中英

python类型注释的参数化联合

[英]Parametrized Union for python type annotations

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

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

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

x: Union[SomeClass, int]

我只需要写

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

我必须继承Type吗? 如果是这样,如何去做呢?

如果我理解正确,您只需要一个TypeVar实例,例如

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]

参考

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM