title: Python decorator with instantiation-time variable?
body: <p>I want to make a decorator that creates a new function/method that makes use of an object <code>obj</code>. If the decorated object is a function, <code>obj</code> must be instantiated when the function is created. If the decorated object is a method, a new <code>obj</code> must be instantiated and bound to each instance of the class whose method is decorated. I can't put the decoration in <code>__init__</code> because the decorator modifies the function documentation. I have something like this now, but it only instantiates <code>time</code> once, which is not what I want:</p>
  
  <pre><code>__all__ = ['dec', 'A']
  
  from time import time
  import inspect
  
  def dec(f):
      obj = time() # want to set on object instantiation
      def new(*args, **kwargs):
          f(*args, **kwargs) # Validate against definition so it doesn't go
                             # out of sync
          print obj
          # ...
      try:
          d = inspect.getsourcelines(f)
      except IOError:
          d = "&lt;unable to fetch definition&gt;"
      else:
          d = d[0][1].rstrip('\n').rstrip(':').lstrip(' ').lstrip('def')
      new.__doc__ = d + "\n" + (f.__doc__ or '')
      return new
  
  class A(object):
      @dec
      def f(self, x):
          """something"""
          print '%s.f(%s)' % (self, x)
  
  if __name__ == '__main__':
      A().f(123)
      A().f(123)
      A().f(123)
  </code></pre>
  
  <p>My idea to solve this is to check if the object passed to the decorator takes an argument <code>self</code>, if so, return a method that binds <code>obj</code> to <code>self</code> if it's not already there, and then uses <code>self.obj</code>. And then if there is no <code>self</code> argument to the object passed to the decorator, just instantiate <code>obj</code> inside the decorator and return a function that makes use of that.</p>
  
  <p>However... what I said doesn't really work for me because in my real decorator, I return an object that is derived from <code>list</code> and has a <code>__call__</code> attribute. Furthermore in the real decorator, <code>self</code> is not even defined in the objects that get decorated by it because they don't make use of their instance variables (what I'm <em>really</em> decorating are just events to be subscribed to by external objects, the events have documented signatures).</p>
  
  <p>Edit: Actually, if there's a way to make a <code>list</code> subclass instance get bound to an instance so that it's <code>__call__</code> attribute implicitly receives the class instance (like in any normal instance method), this would be a perfect solution, this was what I was originally trying to figure out how to do. But maybe there is an even better solution such that I don't have to define the decorated methods with the <code>self</code> attribute? Either is perfect.</p>