Currying decorator in python

2020-01-29 05:51发布

I am trying to write a currying decorator in python, and I think I've got the general idea down, but still got some cases that aren't working right...

def curry(fun):

    cache = []
    numargs = fun.func_code.co_argcount

    def new_fun(*args, **kwargs):
        print args
        print kwargs
        cache.extend(list(args))

        if len(cache) >= numargs:   # easier to do it explicitly than with exceptions

            temp = []
            for _ in xrange(numargs):
                temp.append(cache.pop())
            fun(*temp)

    return new_fun


@curry
def myfun(a,b):
    print a,b

While for the following case this works fine:

myfun(5)
myfun(5)

For the following case it fails:

myfun(6)(7)

Any pointers on how to correctly do this would be greatly appreciated!

Thanks!

9条回答
够拽才男人
2楼-- · 2020-01-29 06:26

Many of the answers here fail to address the fact that a curried function should only take one argument.

A quote from Wikipedia:

In mathematics and computer science, currying is the technique of translating the evaluation of a function that takes multiple arguments (or a tuple of arguments) into evaluating a sequence of functions, each with a single argument (partial application).

Choosing to decorate it with recursion and without co_argcount makes for a decently elegant solution.

from functools import partial, wraps, reduce

def curry(f):
    @wraps(f)
    def _(arg):
        try:
            return f(arg)
        except TypeError:
            return curry(wraps(f)(partial(f, arg)))
    return _

def uncurry(f):
    @wraps(f)
    def _(*args):
        return reduce(lambda x, y: x(y), args, f)
    return _

As shown above, it is also fairly trivial to write an uncurry decorator. :) Unfortunately, the resulting uncurried function will allow any number of arguments instead of requiring a specific number of arguments, as may not be true of the original function, so it is not a true inverse of curry. The true inverse in this case would actually be something like unwrap, but it would require curry to use functools.wraps or something similar that sets a __wrapped__ attribute for each newly created function:

def unwrap(f):
    try:
        return unwrap(f.__wrapped__)
    except AttributeError:
        return f
查看更多
做个烂人
3楼-- · 2020-01-29 06:28

Here is my version of curry that doesn't use partial, and makes all the functions accept exactly one parameter:

def curry(func):
"""Truly curry a function of any number of parameters
returns a function with exactly one parameter
When this new function is called, it will usually create
and return another function that accepts an additional parameter,
unless the original function actually obtained all it needed
at which point it just calls the function and returns its result
""" 
def curried(*args):
    """
    either calls a function with all its arguments,
    or returns another functiont that obtains another argument
    """
    if len(args) == func.__code__.co_argcount:
        ans = func(*args)
        return ans
    else:
        return lambda x: curried(*(args+(x,)))

return curried
查看更多
对你真心纯属浪费
4楼-- · 2020-01-29 06:31

The source code for curry in the toolz library is available at the following link.

https://github.com/pytoolz/toolz/blob/master/toolz/functoolz.py

It handles args, kwargs, builtin functions, and error handling. It even wraps the docstrings back onto the curried object.

查看更多
登录 后发表回答