我有一个decorator类,但在添加类型注释时遇到了问题
import functools
class LogInfo:
def __init__(self, environment: str):
self.environment = environment
def __call__(self, func):
@functools.wraps(func)
def decorated(*args, **kwargs):
# My Stuff goes here...
return func(*args, **kwargs)
return decorated
我能得到的最接近的是:
import functools
from collections import Callable
from typing import TypeVar, Any
GenericReturn = TypeVar("GenericReturn")
GenericCallable = TypeVar("GenericCallable", bound=Callable[..., GenericReturn])
class LogInfo:
def __init__(self, environment: str) -> None:
self.environment = environment
def __call__(self, func: GenericCallable) -> GenericCallable:
@functools.wraps(func)
def decorated(*args: Any, **kwargs: Any) -> GenericReturn:
# My Stuff goes here...
return func(*args, **kwargs)
return decorated # LINE 29
但我仍然得到这个错误:
29: error: Incompatible return value type (got "Callable[..., Any]", expected "GenericCallable")
删除@functools.wraps(func)
会将错误更改为:
29: error: Incompatible return value type (got "Callable[[VarArg(Any), KwArg(Any)], GenericReturn]", expected "GenericCallable")
这是一个不错的解决方案:
我们可以使用以下代码来测试这一点:
正如所料,我们得到了这个
mypy
错误:还有一些可以改进的地方:
return cast(T, decorated)
很难看李>相关问题 更多 >
编程相关推荐