Automatically decorating every instance method in a class

Posted by max on Stack Overflow See other posts from Stack Overflow or by max
Published on 2012-04-08T23:01:08Z Indexed on 2012/04/08 23:28 UTC
Read the original article Hit count: 185

Filed under:
|
|
|

I want to apply the same decorator to every method in a given class, other than those that start and end with __.

It seems to me it should be doable using a class decorator. Are there any pitfalls to be aware of?

Ideally, I'd also like to be able to:

  1. disable this mechanism for some methods by marking them with a special decorator
  2. enable this mechanism for subclasses as well
  3. enable this mechanism even for methods that are added to this class in runtime

[Note: I'm using Python 3.2, so I'm fine if this relies on features added recently.]

Here's my attempt:

_methods_to_skip = {}

def apply(decorator):
  def apply_decorator(cls):
    for method_name, method in get_all_instance_methods(cls):
      if (cls, method) in _methods_to_skip:
        continue
      if method_name[:2] == `__` and method_name[-2:] == `__`:
        continue
      cls.method_name = decorator(method)
  return apply_decorator

def dont_decorate(method):
  _methods_to_skip.add((get_class_from_method(method), method))
  return method

Here are things I have problems with:

  • how to implement get_all_instance_methods function
  • not sure if my cls.method_name = decorator(method) line is correct
  • how to do the same to any methods added to a class in runtime
  • how to apply this to subclasses
  • how to implement get_class_from_method

© Stack Overflow or respective owner

Related posts about python

Related posts about class