Passing source code to __init__ to override method dynamically (Table driven subclassing)
Ian Sparks
Ian.Sparks at etrials.com
Thu Nov 20 16:19:21 EST 2003
I want to create specialized instances of a base class without declaring descendant classes.
Instead, I want to do the specialization by passing source-code to the constructor of the base-class. This way I can make my program table-driven.
Here's my working (but sucky) code :
PASS = 1
FAIL = 0
class test:
def __init__(self,name,code):
self.name = name
self.source = code
co = compile(code,"<string>",'exec')
exec(co,globals(),self.__dict__)
def execute(self):
print self.__dict__['func'](self)
if __name__ == '__main__':
code = """
def func(self):
print code #fun
print self.name #test self
return PASS #test globals
"""
x = test('my test',code)
x.execute()
Great as far as it goes but I'd rather have something more like :
class test:
def __init__(self,name,code):
....
def execute(self):
"""This should be overridden by passed-in code"""
raise NotImplementedError
then...
code = """
#Note no function declaration, that signature won't change so the code could auto-add it (deal with indent?)
print code
print self.name
return PASS
"""
x = test('my test',code)
x.execute()
Any advice?
More information about the Python-list
mailing list