How can I decorate all functions imported from a file?
<p>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.</p>

<p>I have tried to use <a href="http://stackoverflow.com/questions/6307761/how-can-i-decorate-all-functions-of-a-class-without-typing-it-over-and-over-for">this explanation</a> written by delnan, but I got no success for imported functions.</p>

<p>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 <a href="http://stackoverflow.com/questions/39154006/update-a-list-every-time-a-function-within-a-class-is-executexecuted-with-the-fu">this other question</a> I asked.</p>

<p>Any suggestions to help me with this issue?
Thanks</p>

<p>A little bit of introspection (<a href="https://docs.python.org/3/library/functions.html#dir" rel="nofollow"><code>dir()</code></a>) and dynamic look-up with <a href="https://docs.python.org/3/library/functions.html#getattr" rel="nofollow"><code>getattr()</code></a> and <a href="https://docs.python.org/3/library/functions.html#setattr" rel="nofollow"><code>setattr()</code></a>.</p>

<p>First we iterate over all names found in module and <a href="https://docs.python.org/3/library/types.html#types.FunctionType" rel="nofollow">check for objects that look like functions</a>. After that we simply reassign old function with decorated one.</p>

<p><strong>main.py:</strong></p>

<pre><code>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)
</code></pre>

<p><strong>mymod1.py</strong>:</p>

<pre><code>def f(x):
    print(x)


def g(x, y):
    print(x + y)
</code></pre>

<p><strong>Output:</strong></p>

<pre><code>&lt;function f at 0x101e309d8&gt;
2
&lt;function g at 0x101e30a60&gt;
7
</code></pre>

<p>Process does not goes that smooth if you use star imports (<code>from mymod import *</code>). 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 - <a href="https://www.python.org/dev/peps/pep-0020/" rel="nofollow">because they are one honking great idea</a>.</p>

python wrapper python-decorators