title: Dynamic/runtime method creation (code generation) in Python
body: <p>I need to generate code for a method at runtime. It's important to be able to run arbitrary code and have a docstring.</p>
  
  <p>I came up with a solution combining <code>exec</code> and <code>setattr</code>, here's a dummy example:</p>
  
  <pre><code>class Viking(object):
      def __init__(self):
          code = '''
              def dynamo(self, arg):
                  """ dynamo's a dynamic method!
                  """
                  self.weight += 1
                  return arg * self.weight
              '''
          self.weight = 50
  
          d = {}
          exec code.strip() in d
          setattr(self.__class__, 'dynamo', d['dynamo'])
  
  
  if __name__ == "__main__":
      v = Viking()
      print v.dynamo(10)
      print v.dynamo(10)
      print v.dynamo.__doc__
  </code></pre>
  
  <p>Is there a better / safer / more idiomatic way of achieving the same result?</p>