[英]Parametrized Union for python type annotations
I'd like to define a generic type like the following我想定义一个像下面这样的泛型类型
MyType(OtherType) := Union[SomeClass, OtherType]
So that instead of typing the following to annotate x:这样就不用键入以下内容来注释 x:
x: Union[SomeClass, int]
I'd only have to write我只需要写
x: MyType[int] # or MyType(int) for what it's worth
Do I have to subclass Type
?我必须继承Type
吗? If so, how does one go about doing that?如果是这样,如何去做呢?
If I understood correctly all you need is a TypeVar
instance like如果我理解正确,您只需要一个TypeVar
实例,例如
from typing import TypeVar, Union
class SomeClass:
...
OtherType = TypeVar('OtherType')
MyType = Union[SomeClass, OtherType]
def foo(x: MyType[int]) -> int:
return x ** 2
with code like this placed in test.py
module像这样的代码放在test.py
模块中
$ mypy test.py
gives me给我
test.py:13: error: Unsupported operand types for ** ("SomeClass" and "int")
test.py:13: note: Left operand is of type "Union[SomeClass, int]"
and with fix in foo
并在foo
修复
def foo(x: MyType[int]) -> int:
if isinstance(x, SomeClass):
return 0
return x ** 2
has no issues.没有问题。
If we really need this type of alias I've called it something like如果我们真的需要这种类型的别名,我称之为
SomeClassOr = Union[SomeClass, OtherType]
since自从
SomeClassOr[int]
seems more readable to me than对我来说似乎比
MyClass[int]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.