A simple decorator in Python

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.

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
           #allow to access settings
     return decorator

Some points:

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.


One thought on “A simple decorator in Python

  1. Doh! I was domain searching at namecheap.com and went to type
    in the domain name: http://jineshpaloor.wordpress.
    com/2012/05/01/a-simple-decorator-in-python/ and guess who already
    purchased it? You did! lol j/k. I was about to purchase
    this domain name but noticed it had been taken so I figured I’d come check it out. Nice blog!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s