title: Python: instantiate object in decorator, then mutate it inside the decorated function and finally return it
body: <p>I want to have a decorator <code>build_and_fetch_response</code> which creates a response and wraps around a quasi-session-manager <code>managed_exception</code>, which in turn wraps around the actual business logic function <code>fetch</code>:</p>
  <pre class="lang-py prettyprint-override"><code>from datetime import datetime
  
  
  def build_and_fetch_response(managed_exception):
      def wrapper(*args, **kwargs):
          response = {'errors': []}
          managed_exception(response)
          return response    
      return wrapper
  
  
  @build_and_fetch_response
  def managed_exception(response):
      def outter_wrapper(fetch):
          def inner_wrapper(*args, **kwrags):
              dt = datetime.utcnow()
              try:
                  fetch(dt)
              except Exception as e:
                  response['errors'].append(e)
          return inner_wrapper
      return outter_wrapper
  
  
  @managed_exception
  def fetch(dt):
      print(f'fetching resource, time is: {dt}')
      assert True == False
  </code></pre>
  <p>This produces a quite expected result:</p>
  <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; fetch
  {'errors': []}
  
  &gt;&gt;&gt; fetch()
  Traceback (most recent call last):
    File &quot;&lt;input&gt;&quot;, line 1, in &lt;module&gt;
      fetch()
  TypeError: 'dict' object is not callable
  </code></pre>
  <p>I'd like to keep the creation of response object, session manager and logic separated, so this is a no-go:</p>
  <pre class="lang-py prettyprint-override"><code># what I don't want to do:
  def build_and_fetch_response(managed_exception):
      def wrapper(*args, **kwargs):
          # response is built somewhere inside
          response = managed_exception()
          return response    
      return wrapper
  </code></pre>
  <h2>QUESTION:</h2>
  <p>How could I achieve returning a mutable object which is instantiated inside the top-most decorator and passed as argument to lower decorated functions?</p>