Python Decorators, Superpowers for code

Understanding python decorators is like getting superpowers for your code. Trust me it may seem a little tricky at first but even having a basic understanding of decorators can dramatically increase your productivity, your code readability and of course keep your code on point with DRY principals.

Python decorators allow you to modify or extend the behaviour of a callable without modifying the callable itself. Simple right? Well ok maybe it does not make sense right now but we will try to understand this using a very simple example.

So decorators modify or extend a callable. A callable in python includes functions, method and classes. This is a powerful concept and can be great for use cases like logging, cacheing, error handling and timing functions.

But what are they really. Well they are a function that decorates or wraps another function allowing you to execute code before and/or after that wrapped function executes. It also gives you control over what is returned.

Lets explain clearer with an example function

def crazy_math():
    return "Answer"

Ok so we have a crazy_math function we would like to decorate. For this example we want to print to the screen “STARTING” just before function starts and “ENDING” when the function ends. In order to achieve this we create a decorator like below

def our_decorator(func):
    @functools.wraps(func)
    def inner_function(*args, **kwargs):
        print("STARTING")
        func(*args, **kwargs)        
        print("ENDING")
    return inner_function

Ok so now we just need to apply this decorator to out crazy_math function which is super simple.

@our_decorator
def crazy_math():
    return "Answer"

And the output will be

>STARTING
>Answer
>ENDING

A very simple example I know but this should at least give you an idea of the concept of how a decorator can be used and spark a few use cases where you could use them to improve and supercharge your code. Theres loads of material out there if you want to dig deeper on the more advanced use cases of decorators and we encourage you to do so.

Also if you want some examples of some generic decorators we use on most projects have a look at our post on that here TBD

With great power comes great responsibility, use your new powers wisely

The Green Guy

Experienced Software engineer working on a wide range of technologies. Always eager to acquire new skills and share learnings. Also fully qualified carpenter and I really enjoy tinkering with projects to merge software solutions to real life scenarios to enhance and automate our ever changing world :D

You may also like...