Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does a Python decorator do, and where is its code? [duplicate]

Possible Duplicate:
Understanding Python decorators

What does a Python decorator do? And where can I see the codes that are running when I add a decorator to a method?

For example, when I add @login_required at the top of a method, does any code replace that line? How exactly does this line check the user session?

like image 367
Kozet Avatar asked Sep 23 '12 13:09

Kozet


People also ask

What does a decorator do in Python?

Decorators provide a simple syntax for calling higher-order functions. By definition, a decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it.

Where are decorators used in Python?

You'll use a decorator when you need to change the behavior of a function without modifying the function itself. A few good examples are when you want to add logging, test performance, perform caching, verify permissions, and so on. You can also use one when you need to run the same code on multiple functions.

What does a decorator return Python?

A decorator in Python is any callable Python object that is used to modify a function or a class. A reference to a function "func" or a class "C" is passed to a decorator and the decorator returns a modified function or class.

What is decorator module in Python?

The goal of the decorator module is to make it easy to define signature-preserving function decorators and decorator factories. It also includes an implementation of multiple dispatch and other niceties (please check the docs).


1 Answers

when I add @login_required at the top of a method, does any code replace that line?

Kind of. Adding @login_required before your view function has the same effect as doing this:

def your_view_function(request):
    # Function body

your_view_function = login_required(your_view_function)

For explanations of decorators in Python, see:

  • http://www.python.org/dev/peps/pep-0318/
  • http://wiki.python.org/moin/PythonDecorators#What_is_a_Decorator

So decorator functions accept an original function, and return a function that (probably) calls the original function, but does something else too.

In the case of login_required, I think it checks the request object passed to view functions to see if the user is authenticated.

like image 156
Paul D. Waite Avatar answered Oct 19 '22 12:10

Paul D. Waite