Decorators are very useful functionality in Python. Here am going in a straight forward way to get a quick basic idea about what a decorator means. You can find what is a decorator and more details from here.
Excerpt from python wiki about decorator: A decorator is the name used for a software design pattern. Decorators dynamically alter the functionality of a function, method, or class without having to directly use subclasses or change the source code of the function being decorated.
Lets go through an example.
@login_required def account_settings(request): #some code
Here login_required is a decorator. Decorator is nothing but another function. But it’s functionality is different. While running this code, when the python interpreter see some decorator ( here it is login_required) it calls the decorator with the below function as argument (that means ‘account_settings’ as argument). Then we can do some preprocessing with the function inside decorator. Such as, using the details from function arguments we can check whether user is logined or not, if not logined redirect to login page etc.
In short using a decorator we can do some action before a particular function is called.( can do more than this!).
So how a decorator look like. Am giving a simple outline of a decorator:
def login_required(func_name): def decorator(request, *args, **kwargs): #if not logined: # redirect to log in page #else: #allow to access settings return decorator
1) The inner function name ‘decorator’ is optional. You can choose a different name also. But you should return that name in the end. That means if you use the name ‘myfunc’ as function name, then you should return ‘myfunc’.
2) If you are sure about the number of parameter and its type you can use it directly as inner function (here ‘decorator’) parameter. If you know there should be two parameters(say ‘a’ and ‘b’ ) for account_settings function, then you can define inner function as ‘decorator(a,b)’ .
if you want to know more about decorators, this is a good tutorial.