Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

Dynamic/runtime method creation (code generation) in Python

I need to generate code for a method at runtime. It's important to be able to run arbitrary code and have a docstring.

I came up with a solution combining exec and setattr, here's a dummy example:

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__

Is there a better / safer / more idiomatic way of achieving the same result?

Answer*

Draft saved
Draft discarded
Cancel
3
  • ‘i’ will be 10 in each instance of dynamo once the loop has finished. The variable is not rebound each time around the loop. This is one of the big gotchas about using closures in Python (and other similar languages). Commented Feb 10, 2009 at 18:41
  • Ah, drat. Thanks for the clarification. Is there a technique that will work? Commented Feb 10, 2009 at 23:55
  • 1
    Justin, for the solution of this gotcha see: stackoverflow.com/questions/233673/lexical-closures-in-python/… Commented Feb 11, 2009 at 15:47

lang-py

AltStyle によって変換されたページ (->オリジナル) /