Nick Carroll

Metabolising caffeine into code

Python Decorators

with one comment

I found this great post on Python Decorators. Decorators were introduced into the python language since 2.4. The post shows the benefits of using a python decorator to improve the efficiency of a function’s runtime using memoization.

Python decorators are also extensively used in Django for authentication. For example, you can use them to decorate a view function so that only logged in users can view certain parts of your site.

from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    # ...

The example code above shows that you only need to add the @login_required decorator above your view function to determine whether or not the current user needs to be authenticated before the view can be displayed.

Written by Nick

April 20th, 2008 at 8:26 pm

Posted in Programming

Tagged with

One Response to 'Python Decorators'

Subscribe to comments with RSS or TrackBack to 'Python Decorators'.

  1. Thanks for the link! Decorators are extremely useful–the Django code you post here is classic real-world usage.

    Avinash

    20 Apr 08 at 8:51 pm

Leave a Reply