Here's the gist of what I'm trying to do. I have a list of objects, and I know they have an instance method that looks like:
def render(self, name, value, attrs)
# Renders a widget...
I want to (essentialy) decorate these functions at runtime, as I'm iterating over the list of objects. So that their render functions become this:
def render(self, name, value, attrs)
self.attrs=attrs
# Renders a widget...
Two caveats:
An example here: http://wiki.python.org/moin/PythonDecoratorLibrary
Shows how to add a new instance method to a class. The difference here is I want to fall through to the original method after I've memorized that attrs parameter.
def decorate_method(f):
def wrapper(self, name, value, attrs):
self.attrs = attrs
return f(self, name, value, attrs)
return wrapper
def decorate_class(c):
for n in dir(c):
f = getattr(c, n)
if hasattr(f, 'im_func'):
setattr(c, n, decorate_method(f.im_func))
You'll probably need some other test to skip methods with a different signature, but, apart from that, decorate_class(whatever) should do what you want on any given class whatever.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With