使用diskcache.Cache.memoize装饰器时mypy报未类型化装饰器错误
解决diskcache.Cache.memoize导致mypy类型检查报错的问题
方案1:安装diskcache的类型存根包
diskcache官方类型定义可能不完善,安装第三方维护的类型存根包能让mypy正确识别装饰器类型:
pip install types-diskcache
安装后重新运行mypy,多数情况下错误会自动消失。
方案2:用typing.cast明确函数类型
不想额外安装包的话,可通过cast强制指定装饰后函数的类型,让mypy认可其类型信息:
import datetime import pathlib from typing import cast, Callable from diskcache import Cache DEFAULT_CACHE_DIR = pathlib.Path.home() / ".cache" / "hub-cli" cache = Cache(DEFAULT_CACHE_DIR) def _get_local_network_connections() -> list[dict[str, str]]: # 原函数逻辑 return [] # 用cast指定装饰后函数的类型 get_local_network_connections = cast( Callable[[], list[dict[str, str]]], cache.memoize(typing=True, expire=datetime.timedelta(minutes=10).total_seconds())(_get_local_network_connections) )
方案3:自定义类型化装饰器封装
通过泛型TypeVar定义装饰器,保留原函数的类型信息,同时忽略内部的类型检查警告:
import datetime import pathlib from typing import Callable, TypeVar from diskcache import Cache DEFAULT_CACHE_DIR = pathlib.Path.home() / ".cache" / "hub-cli" cache = Cache(DEFAULT_CACHE_DIR) # 定义泛型类型变量,绑定到可调用对象 T = TypeVar("T", bound=Callable) def typed_memoize(*args, **kwargs) -> Callable[[T], T]: def decorator(func: T) -> T: # 忽略返回值的类型检查,确认装饰后函数类型与原函数一致 return cache.memoize(*args, **kwargs)(func) # type: ignore[return-value] return decorator @typed_memoize(typing=True, expire=datetime.timedelta(minutes=10).total_seconds()) def get_local_network_connections() -> list[dict[str, str]]: # 原函数逻辑 return []
方案4:临时忽略类型警告(不推荐)
如果只是临时绕过检查,可在装饰器上方添加类型忽略注释,但这会跳过该位置的类型检查,不建议长期使用:
import datetime import pathlib from diskcache import Cache DEFAULT_CACHE_DIR = pathlib.Path.home() / ".cache" / "hub-cli" cache = Cache(DEFAULT_CACHE_DIR) # 忽略装饰器未类型化的警告 @cache.memoize(typing=True, expire=datetime.timedelta(minutes=10).total_seconds()) # type: ignore[misc] def get_local_network_connections() -> list[dict[str, str]]: ....
内容的提问来源于stack exchange,提问作者Matthew Sparks
相关产品推荐
相关产品推荐

