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.
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
A little bit of introspection (
dir()
) and dynamic look-up withgetattr()
andsetattr()
.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:
mymod1.py:
Output:
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.