title: Applying decorator to all functions in a python package
body: <p>My question is very similar to <a href="https://stackoverflow.com/q/8951787/2593236">this one</a>, but in my case the accepted answer does not decorate all the functions in the package when they are used within the the package and I'm not sure why.</p>
  <p>For example, I have a project set up like this:</p>
  <pre><code>project/
      package/ 
          __init__.py
          module_a.py
          module_b.py
      main.py
  </code></pre>
  <p><code>__init__.py</code></p>
  <pre><code>from .module_a import *
  from .module_b import *
  
  import types
  # This is the decorator that will be used
  from functools import lru_cache
  
  for name, obj in list(globals().items()):
      if isinstance(obj, types.FunctionType):
          globals()[name] = lru_cache(maxsize=100)(obj)
  </code></pre>
  <p><code>module_a.py</code></p>
  <pre><code>from .module_b import b
  
  def a(arg):
      return b
  </code></pre>
  <p><code>module_b.py</code></p>
  <pre><code>def b(arg):
      return arg
  </code></pre>
  <p><code>main.py</code></p>
  <pre><code>import package
  
  print(package.a.cache_info())
  print(package.a(None).cache_info())
  print(package.b.cache_info())
  </code></pre>
  <p>When the package is imported, <code>__init__.py</code> decorates the functions in <code>globals</code> just fine when stepping through the code. However, if I execute <code>main.py</code> I get the following error:</p>
  <pre><code>C:\Users\pbreach\Anaconda3\python.exe C:/Users/pbreach/PycharmProjects/project/main.py
  Traceback (most recent call last):
  CacheInfo(hits=0, misses=0, maxsize=100, currsize=0)
    File &quot;C:/Users/pbreach/PycharmProjects/project/main.py&quot;, line 4, in &lt;module&gt;
      print(package.a(None).cache_info())
  AttributeError: 'function' object has no attribute 'cache_info'
  </code></pre>
  <p>Which would mean that <code>b</code> is not decorated when imported from <code>module_b</code> in <code>module_a</code>.</p>
  <p>Why does this only happen in the second line? What might be a way to accomplish this?</p>
  <p>I am fine with doing the decorating either during import in <code>__init__.py</code> or in <code>main.py</code>, but would rather not have to apply the decorator inside each module in <code>package</code> as in my case there are quite a few of them.</p>
  <h1>EDIT:</h1>
  <p>I think the issue is because <code>globals</code> in <code>__init__.py</code> is a different namespace than when <code>b</code> is imported into <code>module_a</code> meaning there are two different instances of the same function. Is there a way around this?</p>