Callable 是无效的基数 class?
Callable is invalid base class?
有人可以解释为什么要继承未参数化和参数化的 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 时会引发 Foo
和 Bar
的错误:
tmp.py:13: error: Invalid base class
tmp.py:19: error: Invalid base class
部分原因是 classes 在运行时不能真正从函数或可调用对象继承,部分原因是您不需要显式继承 Callable
表示 class 是可调用的。
例如,以下程序使用 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
基本上,如果 class 有一个 __call__
方法,则隐含地假设 class 也是一个可调用的方法。
有人可以解释为什么要继承未参数化和参数化的 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 时会引发 Foo
和 Bar
的错误:
tmp.py:13: error: Invalid base class
tmp.py:19: error: Invalid base class
部分原因是 classes 在运行时不能真正从函数或可调用对象继承,部分原因是您不需要显式继承 Callable
表示 class 是可调用的。
例如,以下程序使用 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
基本上,如果 class 有一个 __call__
方法,则隐含地假设 class 也是一个可调用的方法。