我们的框架需要在某些丑陋的样板代码中包含某些函数:

def prefix_myname_suffix(obj):
    def actual():
        print 'hello world'
    obj.register(actual)
    return obj

我认为这可能会被装饰者简化:

@register
def myname():
    print 'hello world'

然而,事实证明这很棘手,主要是因为框架在模块级别寻找某种函数名称模式。

我在装饰者中尝试了以下内容,但无济于事:

current_module = __import__(__name__)
new_name = prefix + func.__name__ + suffix
# method A
current_module[new_name] = func
# method B
func.__name__ = new_name
current_module += func

任何帮助将不胜感激!

有帮助吗?

解决方案

使用

current_module.new_name = func

setattr(current_module, new_name, func)

其他提示

似乎问题的解决方案是使装饰函数充当原始函数。

尝试使用Twisted中的函数 mergeFunctionMetadata ,在此处找到: twisted / python / util.py

它使您的装饰功能成为原始功能,希望让框架选择它。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top