Decorators in python
A decorator is a function that takes a function and returns the decorated function.
Before class-based views
, decorators were the only way to change the behavior of function-based views
. Being wrappers around a function, they cannot change the inner working of the view, and thus effectively treat them as black boxes.
Confused?
There is some syntactic sugar to help you. Use the annotation notation @, as shown in the following login_required
decorator example:
Tip
The following code is exactly the same as the preceding:
Since login_required
wraps around the view, a wrapper function gets the control first. If the user was not logged-in, then it redirects to settings.LOGIN_URL. Otherwise, it executes simple_view
as if it did not exist.
Decorators are less flexible than mixins. However, they are simpler. You can use both decorators and mixins in Django. In fact, many mixins are implemented with decorators.
Built-in Decorators
Python library contains many built-in decorators as a shortcut of defining properties, class method, static methods, etc.
Decorator | Description |
---|---|
@property |
Declares a method as a property's setter or getter methods. |
@classmethod |
Declares a method as a class's method that can be called using the class name. |
@staticmethod |
Declares a method as a static method. |