如何装饰从文件导入的所有函数? [英] How can I decorate all functions imported from a file?
问题描述
我已经创建了许多分为不同文件的函数,现在我想为所有这些函数应用相同的装饰器,而无需修改文件,也无需一一应用装饰器.
I have created many functions that are divided into different files, now I would like to apply the same decorator for all of them without modifying the files and without applying the decorators one by one.
我尝试使用 这个解释 由 delnan 写,但我没有成功导入函数.
I have tried to use this explanation written by delnan, but I got no success for imported functions.
关于装饰器,它必须在每次执行类中的函数时使用函数参数和值更新一个列表,就像 我问的另一个问题.
About the decorator, it must update a list every time a function within a class is executexecuted with the function arguments and values, just like this other question I asked.
有什么建议可以帮助我解决这个问题吗?谢谢
Any suggestions to help me with this issue? Thanks
推荐答案
一点自省 (dir()
) 和使用 getattr()
和 setattr()
.
A little bit of introspection (dir()
) and dynamic look-up with getattr()
and setattr()
.
首先,我们遍历模块中找到的所有名称,然后检查看起来像函数.之后,我们只需将旧函数重新分配给装饰过的函数即可.
First we iterate over all names found in module and check for objects that look like functions. After that we simply reassign old function with decorated one.
main.py:
import types
import functools
def decorate_all_in_module(module, decorator):
for name in dir(module):
obj = getattr(module, name)
if isinstance(obj, types.FunctionType):
setattr(module, name, decorator(obj))
def my_decorator(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
print(f)
return f(*args, **kwargs)
return wrapper
import mymod1
decorate_all_in_module(mymod1, decorator)
mymod1.py:
def f(x):
print(x)
def g(x, y):
print(x + y)
输出:
<function f at 0x101e309d8>
2
<function g at 0x101e30a60>
7
如果您使用星型导入(from mymod import *
),则过程不会那么顺利.原因很简单——因为所有的名字都放在一个大包里,而且它们的来源没有区别,你需要很多额外的技巧来找到你想要修补的确切内容.但是,这就是我们使用命名空间的原因 - 因为它们是一个很棒的主意.
Process does not goes that smooth if you use star imports (from mymod import *
). Reason is simple - because all names are in one huge bag and there no differentiation on where they come from, you need a lot of additional tricks to find what exactly you want to patch. But, well, that's why we use namespaces - because they are one honking great idea.
这篇关于如何装饰从文件导入的所有函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!