5 Helpful Python Decorator Use Cases

By on 3 August 2021

Some time ago I asked on Twitter:

I was curious what you use #Python decorators for? 

And I got quite an amazing / insightful response:


The obvious next step for me was to look at some examples / use cases.

So below are 5 useful applications of decorators.

Study them, then apply similar things to your own work.

1. De-duplicate code

The first one was easiest, because @prashanttgs posted a great example:

It’s easier for me to do:

@conditional_function 
def fun(): 
...

… for multiple functions than doing this:

def fun():     
    if conditional_function ...

To me this shows the benefit of abstracting away repeated logic to make your functions (classes) leaner.
 

2. Protect against bad inputs

This is a great use case highlighted by @Halmsy

And a good example is the pydantic module and its validator decorator (@mikehawryluk):

https://github.com/samuelcolvin/pydantic/blob/master/pydantic/decorator.py#L42

3. pytest

As per @brianokkenpytest fixtures and marks, including parametrization 

Yep we use those decorators every day and we love them.

Source code of the fixture decorator: 

https://github.com/pytest-dev/pytest/blob/master/src/_pytest/fixtures.py#L1271

4. Logging

@Kay_Hoogland pointed to a cool project called memo.

There we see a cool time_taken decorator:

https://github.com/koaning/memo/blob/main/memo/_util.py

We also added a small timer decorator tip ourselves this week:

5. Authentication

It’s interesting to look at the decorators used for access control in major web frameworks:

https://flask.palletsprojects.com/en/1.1.x/patterns/viewdecorators/

https://github.com/django/django/blob/master/django/contrib/auth/decorators.py


Additionally here are two decorators you’ll find in the Standard Library:

  • @property to make computed attributes or control attribute access, see examples here and here. We also covered them in this article.
  • @classmethod which you can use to add alternative constructors to your class, see an example here.

I hope this has given you some inspiration to use this powerful design pattern more in your work.

If you want to write some of your own, check out the dedicated Decorators Learning Path on our platform:

Code up some decorators on our CodeChalleng.es Python exercise platform.
Your Python toolkit won’t be the same again after learning about two important patterns: decorators and context managers. You can code 12 related Bites on our platform …

OK that’s a wrap (Julian had me put that in, kidding [no he’s not! – Julian])

Happy coding!

— Bob

Want a career as a Python Developer but not sure where to start?