Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decorating Instance Methods in Python

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:

  1. The render function is part of django. I can't put a decorator inside their library (well I could, but then I have to maintain and migrate this change).
  2. It's an instance method.

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.

like image 743
Koobz Avatar asked Dec 01 '25 09:12

Koobz


1 Answers

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.

like image 122
Alex Martelli Avatar answered Dec 04 '25 01:12

Alex Martelli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!