动态地将功能添加到Python模块 [英] dynamically adding functions to a Python module

查看:107
本文介绍了动态地将功能添加到Python模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们的框架要求将某些功能包装在一些难看的样板代码中:

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

任何帮助将不胜感激!

推荐答案

使用任一

current_module.new_name = func

setattr(current_module, new_name, func)

这篇关于动态地将功能添加到Python模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆