Dynamic/runtime method creation (code generation) in Python
Posted
by Eli Bendersky
on Stack Overflow
See other posts from Stack Overflow
or by Eli Bendersky
Published on 2009-02-10T17:40:05Z
Indexed on
2010/03/29
16:53 UTC
Read the original article
Hit count: 384
Hello,
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?
© Stack Overflow or respective owner