定义一个完整的模块的Python装饰器 [英] Defining Python decorators for a complete module
问题描述
我有一个包含许多功能(超过25个)的模块。我想向每个函数添加一个通用的装饰器函数。正常的方法是在每个函数上方添加一个@decorator行,但是我想知道是否有更好的方法?也许我可以在模块顶部或其他地方声明一个全局装饰器?更改,因此修改模块对我而言并不理想。
谢谢。
如果您的装饰器称为 my_decorator
###装饰上述所有函数
,在globals()中为k,v导入类型$ b $b。items():如果isinstance(v,types.FunctionType):
globals()[ k] = my_decorator(v)
导入后也可以将其应用于模块
导入othermodule
导入类型
for vars(othermodule).items()中的k,v:item():
如果isinstance(v,types.FunctionType):
vars(othermodule)[k] = my_decorator(v)
I have a module which contains a lot of functions (more than 25). I want to add a common decorator function to each of these functions. The normal way to do is to add a @decorator line above each function, but I was wondering if there is a better way to do it? Probably I can declare a global decorator at the top of the module or something else?
Note that since I am using someone else's code, I want to minimize the number of lines changed, so modifying the module is not ideal for me.
Thanks.
If your decorator is called my_decorator
### Decorate all the above functions
import types
for k,v in globals().items():
if isinstance(v, types.FunctionType):
globals()[k] = my_decorator(v)
You could also apply this to the module after importing it
import othermodule
import types
for k,v in vars(othermodule).items():
if isinstance(v, types.FunctionType):
vars(othermodule)[k] = my_decorator(v)
这篇关于定义一个完整的模块的Python装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!