为什么在 Python 中不允许单一类型约束? [英] Why are single type constraints disallowed in Python?
问题描述
假设你想约束一个类型变量来实现某个接口.你可以这样写:
Suppose you want to constrain a type variable to implement a certain interface. You might write something like so:
from typing import TypeVar, Callable
T = TypeVar('T', Callable)
class Foo(Generic[T]):
...
>> TypeError: A single constraint is not allowed
为什么 Python 对这种类型约束的使用不满意?PEP 484 和 Python 源代码 在这方面没有帮助.
Why is Python unhappy about this use of type constraints? PEP 484 and the Python source code are unhelpful in this regard.
注意:在我的特殊情况下,我对约束类型变量以实现抽象基类感兴趣,但原理是相同的.
Note: in my particular case I am interested in constraining a type variable to implement an abstract base class, but the principle is the same.
推荐答案
您正在寻找 bound
:
T = TypeVar('T', bound=Callable)
来自文档:
类型变量可以使用 bound=
指定上限.这意味着替换(显式或隐式)类型变量的实际类型必须是边界类型的子类,请参阅 PEP 484.
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
的所有实例都只是如果允许 T = TypeVar('T', Callable)
,则可替换为 Callable
.
TypeVar(name, *args)
means that the type has to be one of args
, so all instances of T
would just be replaceable by Callable
if T = TypeVar('T', Callable)
were allowed.
你应该可以在这里看到不同之处(虽然我没有真正尝试过,呵呵):
You should be able to see the difference here (though I didn’t actually try it, heh):
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 中不允许单一类型约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!