可调用的基类无效吗?

时间:2018-10-04 17:42:37

标签: python type-hinting mypy

有人可以解释为什么从未参数化和参数化的Callable继承吗:

from typing import Callable
from typing import NoReturn
from typing import TypeVar


T = TypeVar('T', str, int)
C = Callable[[T], NoReturn]


class Foo(Callable):

    def __call__(self, t: T):
        pass


class Bar(C):

    def __call__(self, t: T):
        pass

当传递给mypy时,对FooBar均产生错误:

tmp.py:13: error: Invalid base class
tmp.py:19: error: Invalid base class

1 个答案:

答案 0 :(得分:1)

部分原因是运行时类不能真正从函数或可调用对象开始继承,部分原因是不需要显式继承Callable来表明某个类是可通话的。

例如,以下程序使用mypy 0.630进行了预期的类型检查:

from typing import Callable, Union, NoReturn, List

class Foo:
    def __call__(self, t: Union[str, int]) -> NoReturn:
        pass


class FooChild(Foo): pass


class Bad:
    def __call__(self, t: List[str]) -> NoReturn:
        pass


def expects_callable(x: Callable[[Union[str, int]], NoReturn]) -> None: 
    pass


expects_callable(Foo())         # No error
expects_callable(FooChild())    # No error
expects_callable(Bad())         # Error here: Bad.__call__ has an incompatible signature

基本上,如果类具有__call__方法,则隐式假定该类也是可调用的。