我在GitHub上遇到了this interesting snippet,他们讨论了函数,并决定尝试添加注释。到目前为止,我有以下内容。
from typing import cast, Callable, TypeVar, Any, Union
from functools import wraps
U = TypeVar('U')
def curry(f: Callable[..., U]) -> Callable[..., U]:
@wraps(f)
def curry_f(*args: Any, **kwargs: Any) -> Union[Callable[..., U], U]:
if len(args) + len(kwargs) >= f.__code__.co_argcount:
return f(*args, **kwargs)
# do I need another @wraps(f) here if curry_f is already @wrapped?
def curried_f(*args2: Any, **kwargs2: Any) -> Any:
return curry_f(*(args + args2), **{**kwargs, **kwargs2})
return cast(U, curried_f)
return curry_f
@curry
def foo(x: int, y: str) -> str:
return str(x) + ' ' + y
foo(5)
foo(1, 'hello!')
foo(1)('hello!')
然而,在最后一个例子中,Mypy给出了以下内容。
curry.py:43: error: "str" not callable
我似乎无法想出办法来缓解这个问题。