shabda
Comments
Reactions

Understanding decorators

By : Shabda Raaj

If you used Django for any length of time, you would have come across the login_required decorator. You write @login_required before a view, and it magically becomes accessible only to authenticated users.

Decorators were introduced in python 2.4. PEP 318 is the PEP describing it. At the simplest decorators are nothing but callables returning other callables, and the decorator syntax @decorator is nothing but foo = bar(foo), where both bar and foo are callables.

Let us see some decorators in action.

In [1]: def good_function():
   ...:     print 'I am a good function'
   ...:     
   ...:

In [2]: def decorator(orig_func):
   ...:     def bad_func():
   ...:         print 'I am a bad function'
   ...:     return bad_func
   ...:

In [3]: good_function = decorator(good_function)

In [4]: good_function()
I am a bad function

In [5]: @decorator
   ....: def good_function2():
   ....:     print 'I am a good function'
   ....:     
   ....:

In [6]: good_function2()
I am a bad function

So you can see that the decorated function depended only on the value of the function returned by the decorator.

Here we discarded the function we were passed. Any useful decorator, decorates the original function, so it would use the original function. Let us see an actual decorator which may be useful.

def is_val_positive_deco(orig_func):
        def temp_func(val):
                if val < 0:
                        return 0
                else:
                        return orig_func(val)
        return temp_func

@is_val_positive_deco
def sqrt(val):
        import math
        return math.pow(val, (1.0/2))

print sqrt(-1)
print sqrt(4)

Here we defined an decorator is_val_positive_deco which will make functions return 0, if the argument passed is negative. We can use this decorator to guard against MathErrors.

Class based decorators

Decorators are just callables, and hence can be a class which has __call__ method. Sometimes they are easier to understand and reason about(than decorators written as functions). Lets see one,

class LogArgumentsDecorator(object):
        def __init__(self, orig_func):
                self.orig_func = orig_func
                print 'started logging: %s' % orig_func.__name__

        def __call__(self,  *args, **kwargs):
                print 'args: %s' % args
                print 'kwargs:%s'% kwargs
                return self.orig_func(*args, **kwargs)

@LogArgumentsDecorator      
def sum_of_squares(a, b):
        return a*a + b*b

print sum_of_squares(3, b=4)

This outputs,

started logging: sum_of_squares
args: 3
kwargs:{'b': 4}
25

Lets see what happens when we do,

@LogArgumentsDecorator      
def sum_of_squares(a, b):

This is equivalent to

sum_of_squares = LogArgumentsDecorator(sum_of_squares)

At this point, we created a new LogArgumentsDecorator object, so LogArgumentsDecorator.__init__(self, sum_of_squares) gets called. Hence print 'started logging: %s' % orig_func.__name__ line is executed.

When we do sum_of_squares(...)

LogArgumentsDecorator.__call__ gets called with the passed values, where we print the arguments and call the original function.

Here is one more example of a class based decorator. Here we rewrite(sort of, anyway) Django's login_required decorator as a class based decorator.

class LoginRequiredDecorator(object):
def __init__(self, orig_func):
    self.orig_func = orig_func

def __call__(self, request, *args, **kwargs):
    if request.user.is_authenticated():
        self.orig_func(request, *args, **kwargs)
    else:
        return HttpResponseRedirect(reverse('...'))

Similar to above, it takes the view function, during __init__. When the request comes, __call__ makes sure that user is authenticated, and takes action appropriately.

Resources Decorator Library Pep 318


Subscribe to The Uswaretech Blog where we will be writing the next part of this tutorial explaining more complex decorators, decorators which take arguments, decorator factories and more. Or follow us on twitter.


Related Posts


Can we help you build amazing apps? Contact us today.

Topics : python tips

Comments

whiteinge

Excellently and very simply described. Thanks!

commmenttor
vernomcrp 13th July, 2009

this is excellent article, that lets me know deeply about decorator , thank :)

commmenttor
john 22nd July, 2009

Django for any length of time has been a good login period.Only the authorised subcribers are being benefitted only by login .Decorators were introduced in python 2.4. PEP 318 is the PEP describing it.

commmenttor
Dhruv

nice tutorial

commmenttor
ba

The link to the PEP leads to a 404 page on this blog :)

commmenttor
shabda

ba: Fixed it. Thanks.

commmenttor
Kovid 30th June, 2010

very good explanation .But something about the parameter passing is missing...
i.e. in the second example of @is_val_positive_deco.
The passing value of function is is_val_positive_deco(val) is not explained clearly.

commmenttor
Abhishek 21st May, 2012

very nice tutorial.
one small doubt i had was--

if request.user.is_authenticated():
self.orig_func(request, *args, **kwargs)

shouldn't it be

if request.user.is_authenticated():
return self.orig_func(request, *args, **kwargs)

commmenttor
john 16th July, 2012

Thanks - I followed a number of links to try to explain python decorators and this was the first that gave a simple and clear explanation.

commmenttor
foo 22nd July, 2012

thanks you for your explanation! very helpful!

commmenttor
yaseen 20th June, 2013

awesome thanks for the beautiful blog it helped me to understand decorators

commmenttor
Sawan Gupta 6th July, 2013

Thanks, that was a very good blog...

commmenttor

Reactions

alexisbellido

Understanding decorators in Python http://ff.im/-4QkTa

This comment was originally posted on Twitter

mixdev

One of the hidden gems of webframeworks: Decorators (You like to decorate ANY stuff. don’t ya?) http://tr.im/t7TP

This comment was originally posted on Twitter

killingmichael

@docdawning start here: http://bit.ly/rGWBz :) if you want a specific starting point with django/gae D me. #python #appengine #django

This comment was originally posted on Twitter

AtlantaWebsite

Understanding decorators — The Uswaretech Blog – Django Web…:  Bookmark this on Delicious – Saved by jamessnel.. http://bit.ly/Dt2JL

This comment was originally posted on Twitter

Post a comment Name :

Email :

Your site url:

Comment :

© Agiliq, 2009-2012