python - 从包装类推断类型注释
问题描述
鉴于以下类关系,我希望 mypy 能够推断出它x
是 type int
。泛型和 TypeVars 在这里似乎没有太大帮助。ParamSpec 看起来很有希望,但 mypy 还不支持它。有任何想法吗?
from typing import Generic, TypeVar
T = TypeVar('T')
class A:
def __call__(self) -> int:
...
class Wrapper(Generic[T]):
def __init__(self, typ: T) -> None:
self._typ = typ
def __call__(self) -> ...:
return self._typ()()
x = Wrapper(A)()
解决方案
您可以使用通用回调协议来定义可调用对象。协变TypeVar
参数化协议和通用包装类。像这样:
from typing import Generic, TypeVar, Protocol, Type
T = TypeVar('T', covariant=True)
class CallableProto(Protocol[T]):
def __call__(self) -> T:
...
class A:
def __call__(self) -> int:
...
class Wrapper(Generic[T]):
def __init__(self, typ: Type[CallableProto[T]]) -> None:
self._typ = typ
def __call__(self) -> T:
return self._typ()()
x = Wrapper(A)()
# reveal_type(x) # Revealed type is "builtins.int*"
推荐阅读
- python - Matplotlib 多个子图图形间距按要求
- javascript - 无法从导入模块的类型文件中解析打字稿类,但可以使用绝对路径
- android - 如何将振动动画和设备振动设置为edittext?
- list - 在 Python 中转换为范围
- sql - 在 SQL Server 中加密列上的运算符搜索
- unity3d - GetAxis 不工作(没有感应到我的输入?)
- javascript - 在Angular 5中将数据读/写到文件(文本文件)中
- vue.js - vue.js 中的路由错误 - 访问 XMLHttpRequest
- javascript - 使用 tabindex="0" 会对其他元素产生影响
- c++ - 如何设置 SFML+CMake+代码块?