向 Python 模块动态添加函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1621350/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
dynamically adding functions to a Python module
提问by AnC
Our framework requires wrapping certain functions in some ugly boilerplate code:
我们的框架需要将某些功能包装在一些丑陋的样板代码中:
def prefix_myname_suffix(obj):
def actual():
print 'hello world'
obj.register(actual)
return obj
I figured this might be simplified with a decorator:
我认为这可以通过装饰器来简化:
@register
def myname():
print 'hello world'
However, that turned out to be rather tricky, mainly because the framework looks for a certain pattern of function names at module level.
然而,结果证明这相当棘手,主要是因为框架在模块级别寻找特定的函数名称模式。
I've tried the following within the decorator, to no avail:
我在装饰器中尝试了以下操作,但无济于事:
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
Any help would be appreciated!
任何帮助,将不胜感激!
回答by Oren S
use either
使用
current_module.new_name = func
or
或者
setattr(current_module, new_name, func)
回答by truppo
It seems the solution to your problem would be to make the decorated function act as the original function.
您的问题的解决方案似乎是使装饰函数充当原始函数。
Try using the function mergeFunctionMetadata
from Twisted, found here:
twisted/python/util.py
尝试使用mergeFunctionMetadata
Twisted 中的函数,在此处找到:
twisted/python/util.py
It makes your decorated function act as the original, hopefully making the framework pick it up.
它使您的装饰函数充当原始函数,希望使框架能够接收它。