Help with some code

Ian Sparks Ian.Sparks at etrials.com
Wed Nov 19 22:29:49 EST 2003


Hi,
 
I want to create specialized instances of a base class without having to :
 
1. declare a descendant class
2. create an instance of that descendant class. 
 
Instead, I want to :
 
1. Create an instance of the base class, specializing it by passing source-code to its constructor.
 
Here's what I have so far :
 
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()
        
It works and it's great that I can do this with python at all but I wonder if there's a cleaner way to do this. 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