How to Combine Two Python Decorators2020-04-01
Imagine you have some Django views using the same two decorators:
It’s a bit repetitive, and prone to mistakes on new views, such as using the wrong order, or missing one. You can instead combine them into one decorator.
In Python, the decorator syntax is a shortcut for calling the decorator and storing its result in the same name. For example, this snippet:
is the same as:
Therefore to combine these decorators, you can implement a new function that calls each of the decorators in turn like this. To maintain the same order, you should call them “from the inside out”. So you can make a combined decorator function like this:
You can then apply it to views like this:
Some decorators take arguments, for which this technique needs expanding a bit.
For example, Django’s
require_http_methods is a general version of
require_GET that takes an argument for the methods.
If you had some repetition using it:
Then, you create a similar combination decorator, calling
require_http_methods with its arguments in the same way:
Finally, you could expand the combined decorator to pass arguments through. This means the outer function, which takes the arguments, needs to return an inner decorator function that will be applied to the target. For example, to allow configuring the required methods and whether a login is required in a single decorator:
You can then apply this like:
I hope this helps you DRY out your decorators,
🎉 My book Speed Up Your Django Tests is now up to date for Django 3.2. 🎉
Buy now on Gumroad
One summary email a week, no spam, I pinky promise.
- Simplify Your If Statements That Return Booleans
- Entering a Flaky Context Manager in Python
- Limit Your Try Clauses in Python
Tags: django, python
© 2021 All rights reserved.