Search code examples
pythonsyntaxdecorator

Difference between decorator classes and decorator functions


I guess that's how they are called, but I will give examples just in case.

Decorator class:

class decorator(object):
    def __init__(self, func):
        self.func = func

    def __call__(self, *args, **kwargs):
        print 'something'
        self.func(*args, **kwargs)

Decorator function:

def decorator(func):
    def wrapper(*args, **kwargs):
        print 'something'
        return func(*args, **kwargs)
    return wrapper

Is using one or the other just a matter of taste? Is there any practical difference?


Solution

  • If you can write a function to implement your decorator you should prefer it. But not all decorators can easily be written as a function - for example when you want to store some internal state.

    class counted(object):
        """ counts how often a function is called """
        def __init__(self, func):
            self.func = func
            self.counter = 0
    
        def __call__(self, *args, **kwargs):
            self.counter += 1
            return self.func(*args, **kwargs)
    
    
    @counted
    def something():
        pass
    
    something()
    print something.counter
    

    I've seen people (including myself) go through ridiculous efforts to write decorators only with functions. I still have no idea why, the overhead of a class is usually totally negligible.