【问题标题】:Wrap every function or class method in a Python module by default without decorating every one默认情况下将每个函数或类方法包装在 Python 模块中,而不是每一个都进行装饰
【发布时间】:2016-01-17 02:30:09
【问题描述】:

我有一些代码,每当遇到这样的异常时,我都想从中获取电子邮件。

try:
    f(**kwargs)
except Exception as e:
    # email me the environment

我知道 Python 装饰器可以为此工作,例如:

@check_error
def f()
@check_error
def g()

如果我希望我的模块中的每个代码都被默认包装怎么办?喜欢 def f() 没有@check_error,但我仍然希望能够实现这一点。 理想情况下,该解决方案应适用于函数和类方法。

【问题讨论】:

    标签: python decorator python-decorators


    【解决方案1】:

    您可以内省模块,因此假设 module 是您想要装饰所有功能的模块,您可以执行以下操作:

    import inspect
    for name, f in inspect.getmembers(module, inspect.isfunction):
        setattr(module, name, check_error(f))
    

    您甚至可以在当前模块中使用sys.modules[__name__] 代替module 来执行此操作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-07
      • 1970-01-01
      • 1970-01-01
      • 2015-03-07
      • 2017-03-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多