title: Setting a functools.partial as an instance method in Python
body: <p>I'm using <code>functools.partial</code> to create a closure, and using <code>setattr</code> to make is callable from a class instance. The idea here is to create a set of methods at runtime.</p>
  
  <pre><code>#!/usr/bin/python
  from functools import partial
  
  class MyClass(object):
  
      def __init__(self, val):
          self.val = val
  
      @classmethod
      def generateMethods(self):
          def dummy(conf1, self):
              print "conf1:", conf1
              print "self.val:", self.val
              print
  
          for s in ('dynamic_1', 'dynamic_2'):
              closed = partial(dummy, s)
              setattr(self, "test_{0}".format(s), closed)
  </code></pre>
  
  <p>It seems to me that <code>partial</code> would bind the current value of <code>s</code> to <code>dummy</code>'s first arg, which would free up <code>self</code> to be passed when this is called from an instance.</p>
  
  <p>It's not working how I'd expect</p>
  
  <pre><code>if __name__ == '__main__':
      # Dynamically create some methods
      MyClass.generateMethods()
  
      # Create an instance
      x = MyClass('FOO')
  
      # The dynamically created methods aren't callable from the instance :(
      #x.test_dynamic_1()
      # TypeError: dummy() takes exactly 2 arguments (1 given)
  
      # .. but these work just fine
      MyClass.test_dynamic_1(x)
      MyClass.test_dynamic_2(x)
  </code></pre>
  
  <p>Is it possible to dynamically create methods which are closures, but callable from instances of the class?</p>