如何在 curry 中保存 user_function 的元数据?

问题描述 投票:0回答:1

我有这个代码:

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

我需要名称 curried_function 来匹配我们柯里化的函数的名称:

print(curried_function.__name__)
max

也许我可以使用 functools 包装?但如何呢?

python function metadata functools curry
1个回答
0
投票

可以做:

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([])

但说实话,我不确定这样做是否会产生后果。 functools 库可能有一个很好的解决方案(可能使用

@wrapped
装饰器或类似的东西)。

© www.soinside.com 2019 - 2024. All rights reserved.