python - 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 的建议使用wraps
fromfunctools
可以更接近目标:
使用包裹
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:有人可以帮我吗?
解决方案
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()
推荐阅读
- snowflake-cloud-data-platform - Snowflake 改进了网络上的搜索加入 IP
- python - 使用预定义的一组值创建数据集
- javascript - 将数组显示为分页视图
- ssis - 如何将文件路径及其名称插入 SSIS 的新列中?
- windows - 如何在 Windows 中拦截 DNS 查询
- javascript - 如何从量角器的属性文件中读取多行字符串
- react-native - 更改 react-native 中所选文本的颜色
- javascript - D3 鼠标悬停返回名称
- gem5 - gem5 CPU 型号之间有什么区别,哪一种更适合我的模拟?
- php - call_user_func_array() 期望参数 1 是一个有效的回调,类 'Illuminate\Database\MySqlConnection' 没有方法 'query'