【问题标题】:dynamically adding functions to a Python module向 Python 模块动态添加函数
【发布时间】:2023-03-22 18:57:01
【问题描述】:

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

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

任何帮助将不胜感激!

【问题讨论】:

  • 您需要更彻底地解释一下框架在这些名称中“看起来”的内容和方式。您可能可以覆盖 getattr 或调整模块自己的字典来伪造它,但目前还不能确定。
  • 老实说,我不知道这个框架到底做了什么。 Oren 的小提醒正是我所需要的。

标签: python metaprogramming decorator


【解决方案1】:

使用任一

current_module.new_name = func

setattr(current_module, new_name, func)

【讨论】:

    【解决方案2】:

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

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

    它使您的装饰函数充当原始函数,希望框架能够接受它。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-15
    • 2020-06-07
    • 1970-01-01
    • 2011-02-16
    • 2012-05-04
    • 1970-01-01
    • 2011-04-06
    • 1970-01-01
    相关资源
    最近更新 更多