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 @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:
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:
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
from Planet Python
via read more
No comments:
Post a Comment