描述一个 class 的 TypeVar 必须 subclass 多于一个 class
TypeVar describing a class that must subclass more than one class
我想创建一个类型注释 T
,它描述的类型必须是 class A
和 class 的子class B
.
T = TypeVar('T', bound=A)
仅指定 T
必须是 A
.
的子class
T = TypeVar('T', A, B)
仅指定 T
必须是 A
的子class 或 B
的子class 但 不一定都是。
我实际上想要像 T = TypeVar('T', bound=[A, B])
这样的东西,这意味着 T
必须 class 同时 A
和 B
。有这样做的标准方法吗?
您正在寻找的是交叉路口类型。严格来说,我不相信 Python 的类型注释支持这一点(至少现在还没有)。但是,您可以使用 Protocol
:
得到类似的东西
from typing import Protocol, TypeVar
class A:
def foo(self) -> int:
return 42
class B:
def bar(self) -> bool:
return False
class C(A, B): pass
class D(A): pass
class E(B): pass
class ABProtocol(Protocol):
def foo(self) -> int: ...
def bar(self) -> bool: ...
T = TypeVar('T', bound=ABProtocol)
def frobnicate(obj: T) -> int:
if obj.bar():
return obj.foo()
return 0
frobnicate(C())
frobnicate(D())
frobnicate(E())
Mypy 抱怨:
test.py:26: error: Value of type variable "T" of "frobnicate" cannot be "D"
test.py:27: error: Value of type variable "T" of "frobnicate" cannot be "E"
当然,这需要您自己显式注释所有方法,不幸的是,class ABProtocol(A, B, Protocol): pass
之类的东西是不允许的
我想创建一个类型注释 T
,它描述的类型必须是 class A
和 class 的子class B
.
T = TypeVar('T', bound=A)
仅指定 T
必须是 A
.
T = TypeVar('T', A, B)
仅指定 T
必须是 A
的子class 或 B
的子class 但 不一定都是。
我实际上想要像 T = TypeVar('T', bound=[A, B])
这样的东西,这意味着 T
必须 class 同时 A
和 B
。有这样做的标准方法吗?
您正在寻找的是交叉路口类型。严格来说,我不相信 Python 的类型注释支持这一点(至少现在还没有)。但是,您可以使用 Protocol
:
from typing import Protocol, TypeVar
class A:
def foo(self) -> int:
return 42
class B:
def bar(self) -> bool:
return False
class C(A, B): pass
class D(A): pass
class E(B): pass
class ABProtocol(Protocol):
def foo(self) -> int: ...
def bar(self) -> bool: ...
T = TypeVar('T', bound=ABProtocol)
def frobnicate(obj: T) -> int:
if obj.bar():
return obj.foo()
return 0
frobnicate(C())
frobnicate(D())
frobnicate(E())
Mypy 抱怨:
test.py:26: error: Value of type variable "T" of "frobnicate" cannot be "D"
test.py:27: error: Value of type variable "T" of "frobnicate" cannot be "E"
当然,这需要您自己显式注释所有方法,不幸的是,class ABProtocol(A, B, Protocol): pass
之类的东西是不允许的