默认情况下,将每个函数或类方法包装在Python模块中,而无需修饰每个 [英] Wrap every function or class method in a Python module by default without decorating every one
问题描述
我有一些代码,只要遇到此类异常,我都希望从中获取电子邮件.
I have some code from which I want to get an email whenever it runs into an exception like this.
try:
f(**kwargs)
except Exception as e:
# email me the environment
我知道Python装饰器可以做到这一点,例如:
I know that Python decorators can work for this, like:
@check_error
def f()
@check_error
def g()
如果我希望模块中的每个代码默认都被包装怎么办?喜欢没有 @check_error
的 def f()
,但是我仍然希望能够实现这一目标.理想情况下,该解决方案应同时适用于函数和类方法.
What if I want every code in my module be wrapped by default? Like
def f()
without the @check_error
, but I still want to be able to achieve this.
Ideally, the solution should apply for both functions and class methods.
推荐答案
您可以内省模块,因此假设 module
是要装饰其所有功能的模块,则可以执行以下操作:
You can introspect modules, so assuming module
is the module for which you want to decorate all functions you could do something like this:
import inspect
for name, f in inspect.getmembers(module, inspect.isfunction):
setattr(module, name, check_error(f))
您甚至可以在当前模块中通过对 module
You could even do this in the current module by using sys.modules[__name__]
for module
这篇关于默认情况下,将每个函数或类方法包装在Python模块中,而无需修饰每个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!