Typing a decorator that curries functions

大憨熊 提交于 2021-01-29 12:29:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!