问题
I came across this interesting snippet on GitHub that curries functions and decided to try to add annotations. So far I have the following.
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!')
However, with the last example, Mypy gives the following.
curry.py:43: error: "str" not callable
I can't seem to come up with a way to mitigate this issue.
来源:https://stackoverflow.com/questions/46987933/typing-a-decorator-that-curries-functions