首页 > 解决方案 > Python - 重命名其他函数返回的函数

问题描述

我创建了一个方法create_function,它根据参数返回另一个具有修改行为的函数。我的实现工作正常,但有一件事困扰着我:返回的函数有这个名字<function create_function.<locals>.new_func at ...>。这使得错误消息难以解释,因为create_function在不同的函数上使用会导致它们在引发异常时具有几乎相同的名称。

创建函数

def create_function(func, arguments: dict):
    def new_func(x):
        return func(x, **arguments)

    return new_func


f = create_function(sum, {})
f() # Missing the parameter x should raise exception.

> TypeError: new_func() missing 1 required positional argument: 'x'

我尝试使用装饰器,但效果不佳。

def rename(new_name):
    def decorator(f):
        f.__name__ = new_name
        return f
    return decorator


def create_function(func, arguments: dict):
    @rename("Test")
    def new_func(x):
        return func(x, **arguments)

    return new_func


f = create_function(sum, {})
print(f.__name__)
f()

> Test
> TypeError: new_func() missing 1 required positional argument: 'x'

那么有没有办法将返回函数的名称更改为其他名称new_func

编辑

所以为了更清楚一点,我想在引发错误时显示输入函数的名称(在上面的示例中:sum而不是)。new_func按照 Jiri Baum 的建议使用wrapsfromfunctools可以更接近目标:

使用包裹

from functools import wraps

def create_function(func, arguments: dict):
    @wraps(func)
    def new_func(x):
        return func(x, **arguments)
    
    return new_func


f = create_function(sum, {})
print(f.__name__) # Printing the name of the returned function
f()      # Raising an Type Error on purpose to show the Exception message

> <function sum at .> # This is what I wanted to show up!
> TypeError: new_func() missing 1 required positional argument: 'x'
 # No, here comes new_func again...

那么有没有办法让异常说类似 TypeError: sum() missing 1 required positional argument???

编辑2:有人可以帮我吗?

标签: pythonfunctiontypesfunctional-programmingpython-decorators

解决方案


def create_function(func, arguments: dict):
    def demo(x):
        return func(x, **arguments)

    return demo
f = create_function #assigned function to variable.
f(sum,{}) # function call using varible f

将函数分配给变量但没有 ()。然后在那个变量中,如果有一个参数,那么你必须传递它或者只保留它 var_name()


推荐阅读