Hello,

I am trying to find the way to create and add a method to a class instance
dynamically (ie at run time).

This is one of my try :

import new

class AddMethod:
    def add(self):
        self.id = 10
        code = '''lambda self: self.id'''
        byteCode = compile(code, 'addMethod.py', 'single')
        print byteCode.co_argcount
        function = new.function(byteCode, self.__class__.__dict__)
        method = new.instancemethod(function, self, self.__class__)
        setattr(self, 'getId', method)


if __name__ == '__main__':
    a = AddMethod()
    a.add()
    a.getId()

When running that, I get the following error message (I get the same error whatever
I pass to the kind argument of compile):

Traceback (innermost last):
  File "d:\Program Files\Python\Pythonwin\pywin\framework\scriptutils.py", line 301,
in RunScript
    exec codeObject in __main__.__dict__
  File "E:\Code\Python\god\addMethod.py", line 17, in ?
    a.getId()
TypeError: no arguments expected

So I am trying to know how to create byteCode which needs arguments.

I have tried to replace my code string with the following :

        code = '''
        def getId(self):
            return self.id
        '''


But the I get the following error message:

Traceback (innermost last):
  File "d:\Program Files\Python\Pythonwin\pywin\framework\scriptutils.py", line 301,
in RunScript
    exec codeObject in __main__.__dict__
  File "E:\Code\Python\god\addMethod.py", line 19, in ?
  File "E:\Code\Python\god\addMethod.py", line 10, in add
    method = new.instancemethod(function, self, self.__class__)
  File "<string>", line 2
     def getId(self):
     ^
 SyntaxError: invalid syntax


Any help would be appreciated.




--

Godefroid Chapelle
BubbleNet
30, rue Victor Horta
B-1348 Louvain-la-Neuve (Belgium)
+32 (10) 45 06 46


_______________________________________________
ActivePython mailing list
[EMAIL PROTECTED]
http://listserv.ActiveState.com/mailman/listinfo/activepython

Reply via email to