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
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]
参考
我想像下面这样定义一个通用类型
MyType(OtherType) := Union[SomeClass, OtherType]
这样就不用键入以下内容来注释 x:
x: Union[SomeClass, int]
我只需要写
x: MyType[int] # or MyType(int) for what it's worth
我必须继承 Type
吗?如果是这样,人们该怎么做呢?
如果我没理解错的话,你只需要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]