Hey Pythonista,
I asked this on Twitter the other day:
I was curious what you use #Python decorators for?
And I got quite an amazing / insightful response:
https://twitter.com/bbelderbos/status/1355453621182345216
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 @brianokken: pytest 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:
https://twitter.com/pybites/status/1355744107096846339
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
--
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:
https://codechalleng.es/bites/paths/decorators-context
OK that's a wrap (Julian had me put that in, kidding [no he's not! - Julian])
Happy coding!
-- Bob