run-time construction of methods

Carlo v. Dango oest at soetu.eu
Mon Apr 5 21:07:14 EDT 2004


Hello all.

I am in the need of wrapping certain objects at run-time. My initial 
approach was:

import inspect, new
def make_wrapper(obj, methodName):
     cls = obj.__class__
     wrapmth = getattr(obj, methodName)
     print "************ ", methodName
     def wrapper(self, *args, **kwargs):
         print "**before ", methodName
         return wrapmth(*args, **kwargs)
     return wrapper

class Person(object):
     def __init__(self, age):
         super(Person, self).__init__()
         self.age = age

     def getAge(self):
         return self.age

     def setAge(self, newage):
         """sets the age of the person"""
         self.age = newage

p = Person(33)
setattr(p, "setAge", new.instancemethod(make_wrapper(p,"setAge"), p, 
p.__class__))
p.setAge(22)
print "age is ", p.getAge()



However, reflectional information is gone, such as the __doc__ string, and 
in an interactive environment, when typing a method call of setAge() the 
arguments are specified as "(..., ***)" rather than "(newage)"

I have thus attempted to replace the make_wrapper function with a version 
where the inner function "wrapper" is a string which gets translated into 
a function with an identical signature as the method to wrap.. my closest 
attempt to a real solution is


def make_wrapper(obj, methodName):
     cls = obj.__class__
     wrapmth = getattr(obj, methodName)
     print "************ ", methodName
     wrapperstr = """def wrapper(self, *args, **kwargs):
         print "**before ", methodName
         return wrapmth(*args, **kwargs)"""
     exec(wrapperstr, globals(), locals())
     return wrapper

but I get the error

NameError: global name 'methodName' is not defined

which I don't know how to deal with... inspecting the locals() a 
'methodName' is defined.. Note that my above 'solution' is far from the 
product I want, I just figured I needed to get this to work, before 
fidling with the signature stuff...


does anyone have an idea on how to approach this?


-Carlo
-- 
Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/



More information about the Python-list mailing list