11

say I have a class:

class x:

    def first_x_method(self):
        print 'doing first_x_method stuff...'

    def second_x_method(self):
        print 'doing second_x_method stuff...'

and this decorator

class logger:
    @staticmethod
    def log(func):
        def wrapped(*args, **kwargs):
            try:
                print "Entering: [%s] with parameters %s" % (func.__name__, args)
                try:
                    return func(*args, **kwargs)
                except Exception, e:
                    print 'Exception in %s : %s' % (func.__name__, e)
            finally:
                print "Exiting: [%s]" % func.__name__
        return wrapped

how would I write another decorator otherdecorator so that:

@otherdecorator(logger.log)
class x:

    def first_x_method(self):
        print 'doing x_method stuff...'

    def first_x_method(self):
        print 'doing x_method stuff...'

the same as

class x:
      @logger.log
      def first_x_method(self):
          print 'doing first_x_method stuff...'

      @logger.log
      def second_x_method(self):
        print 'doing second_x_method stuff...'

or in fact replace

@otherdecorator(logger.log)
class x:

with

@otherdecorator 
class x:

where otherdecorator contains all the functionality (I'm not a python person so be gentle)

2
  • What version of Python are you using?
    – detly
    Mar 30, 2011 at 3:57
  • 2.6 and Iron Python (clr 4.0/dlr) Mar 30, 2011 at 8:35

2 Answers 2

21

Unless there is a definite reason to use a class as a decorator, I think it is usually easier to use functions to define decorators.

Here is one way to create a class decorator trace, which decorates all methods of a class with the log decorator:

import inspect


def log(func):
    def wrapped(*args, **kwargs):
        try:
            print("Entering: [%s] with parameters %s" % (func.__name__, args))
            try:
                return func(*args, **kwargs)
            except Exception as e:
                print('Exception in %s : %s' % (func.__name__, e))
        finally:
            print("Exiting: [%s]" % func.__name__)
    return wrapped


def trace(cls):
    # https://stackoverflow.com/a/17019983/190597 (jamylak)
    for name, m in inspect.getmembers(cls, lambda x: inspect.isfunction(x) or inspect.ismethod(x)):
        setattr(cls, name, log(m))

    return cls


@trace
class X(object):
    def first_x_method(self):
        print('doing first_x_method stuff...')

    def second_x_method(self):
        print('doing second_x_method stuff...')


x = X()
x.first_x_method()
x.second_x_method()

yields:

Entering: [first_x_method] with parameters (<__main__.X object at 0x7f19e6ae2e80>,)
doing first_x_method stuff...
Exiting: [first_x_method]
Entering: [second_x_method] with parameters (<__main__.X object at 0x7f19e6ae2e80>,)
doing second_x_method stuff...
Exiting: [second_x_method]
4
  • So presumably I could add the decorator at run time with a settattr on the type to secorate? Mar 30, 2011 at 9:00
  • 1
    @Preet Sangha: Yes, I don't think there would be any problem -- except that instances of the class made before the decorator is applied will not be modified.
    – unutbu
    Mar 30, 2011 at 12:32
  • @unutbu, my Python version is 3.6.8 and the running result is:doing first_x_method stuff... doing second_x_method stuff...
    – Tengerye
    Apr 16, 2019 at 2:26
  • @Tengerye: The code above has now been updated for Python3. The main difference is that in Python3 the method is just a plain function so the predicate needs to be changed to inspect.isfunction instead of inspect.ismethod.
    – unutbu
    Apr 16, 2019 at 12:05
2

Here's a version of the trace decorator implemented as a class which allows for the other use case asked for: passing in the function to decorate all member functions of the decorated class with.

import inspect


def log(func):
    def wrapped(*args, **kwargs):
        try:
            print "Entering: [%s] with parameters %s" % (func.__name__, args)
            try:
                return func(*args, **kwargs)
            except Exception, e:
                print 'Exception in %s : %s' % (func.__name__, e)
        finally:
            print "Exiting: [%s]" % func.__name__
    return wrapped


class trace(object):

    def __init__(self, f):
        self.f = f

    def __call__(self, cls):
        for name, m in inspect.getmembers(cls, inspect.ismethod):
            setattr(cls, name, self.f(m))
        return cls


@trace(log)
class X(object):

    def first_x_method(self):
        print 'doing first_x_method stuff...'

    def second_x_method(self):
        print 'doing second_x_method stuff...'

x = X()
x.first_x_method()
x.second_x_method()
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.