假设你想约束一个类型变量来实现某个接口(interface)。你可以这样写:
from typing import TypeVar, Callable
T = TypeVar('T', Callable)
class Foo(Generic[T]):
...
>> TypeError: A single constraint is not allowed
为什么 Python 对这种类型约束的使用不满意? PEP 484和 Python source code在这方面没有帮助。
注意:在我的特定情况下,我对约束类型变量以实现抽象基类很感兴趣,但原理是相同的。
最佳答案
您正在寻找 bound
:
T = TypeVar('T', bound=Callable)
来自 the docs :
a type variable may specify an upper bound using
bound=<type>
. This means that an actual type substituted (explicitly or implicitly) for the type variable must be a subclass of the boundary type, see PEP 484.
TypeVar(name, *args)
意味着类型必须是 args
之一, 所以 T
的所有实例只能由 Callable
替换如果T = TypeVar('T', Callable)
被允许。
你应该能看出这里的区别(虽然我没有真正尝试过,呵呵):
from typing import Generic, TypeVar, Callable
T = TypeVar('T', Callable, bool)
class Foo(Generic[T]):
value: T
def __init__(self, value: T) -> None:
self.value = value
class Bar:
baz = 5
def __call__(self):
pass
f = Foo(Bar())
print(f.value.baz) # doesn’t typecheck because f.value is only a Callable
关于python - 为什么在 Python 中不允许单一类型约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50185027/