Quick Python: Decorators

Brandon Rozek

March 30, 2020

Geir Arne Hjelle at Real Python wrote a great post called Primer on Python Decorators. I recommend reading that as this post serves mostly as a reminder to myself on how to write a decorator.

I find decorators useful for several reasons

Here is a template for how a decorator is written

import functools

def decorator(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        # Do something before
        value = func(*args, **kwargs)
        # Do something after
        return value
    return wrapper

If your decorator takes arguments then there’s another layer…

def decorator_with_argument(argument):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            # Do something before
            value = func(*args, **kwargs)
            # Do something after
            return value
        return wrapper
    return decorator

Example: Logging

Let’s write a decorator that logs the string returned by the function to a file.

def filelog(filename):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            with open(filename, 'w') as f:
                f.write(func(*args, **kwargs))
        return wrapper
    return decorator

@filelog('log.txt')
def greet(name):
    return f"Hello {name}!"