pythonfunctionmetadatacurryingfunctools

How can I save the metadata of the user_function in curry?


I have this code:

def curry_explicit(function, arity):
    """
    Turning a function from several parameters into a function from one parameter that returns a function from the other parameters:
    function(a,b) --> function(a)(b)
    """
    if arity == 0:
        return function

    def get_args(args):
        if len(args) == arity:
            return function(*args)

        def curry(x):
            return get_args([*args, x])

        return curry

    return get_args([])


user_function = max

curried_function = curry_explicit(user_function, 3)

print(curried_function.__name__)
curry

I need the name curried_function to match the name of the function that we curried:

print(curried_function.__name__)
max

Maybe i can use functools wraps? But how?


Solution

  • You could do:

    def curry_explicit(function, arity):
        """
        Turning a function from several parameters into a function from one parameter that returns a function from the other parameters:
        function(a,b) --> function(a)(b)
        """
        if arity == 0:
            return function
    
        def get_args(args):
            if len(args) == arity:
                return function(*args)
    
            def curry(x):
                func = get_args([*args, x])
                return func
    
            curry.__name__ = function.__name__
            return curry
    
        return get_args([])
    

    But honestly not sure if there are consequences to doing this. The functools library probably has a good solution (likely using the @wraps decorator as you suggested or something similar).