为什么Python中不允许单一类型约束?

alc*_*orn 15 python types python-3.6

假设您想约束一个类型变量来实现某个接口.你可能会这样写:

from typing import TypeVar, Callable

T = TypeVar('T', Callable)

class Foo(Generic[T]):
    ...

>> TypeError: A single constraint is not allowed
Run Code Online (Sandbox Code Playgroud)

为什么Python对这种类型约束的使用不满意?在这方面,PEP 484Python源代码无益.

注意:在我的特定情况下,我感兴趣的是约束一个类型变量来实现一个抽象基类,但原理是相同的.

Ry-*_*Ry- 11

您正在寻找bound:

T = TypeVar('T', bound=Callable)
Run Code Online (Sandbox Code Playgroud)

来自文档:

类型变量可以使用指定上限bound=<type>.这意味着类型变量替换(显式或隐式)的实际类型必须是边界类型的子类,请参阅PEP 484.

TypeVar(name, *args)意味着类型必须是其中之一args,因此所有实例T都可以被Callableif 替换为if 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
Run Code Online (Sandbox Code Playgroud)