5

What does @ mean in Python?

Example: @login_required, etc.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
omg
  • 136,412
  • 142
  • 288
  • 348

6 Answers6

31

It is decorator syntax.

A function definition may be wrapped by one or more decorator expressions. Decorator expressions are evaluated when the function is defined, in the scope that contains the function definition. The result must be a callable, which is invoked with the function object as the only argument. The returned value is bound to the function name instead of the function object. Multiple decorators are applied in nested fashion.

So doing something like this:

@login_required
def my_function():
    pass

Is just a fancy way of doing this:

def my_function():
    pass
my_function = login_required(my_function)

For more, check out the documentation.

Paolo Bergantino
  • 480,997
  • 81
  • 517
  • 436
1

It's a decorator. More here: http://www.ibm.com/developerworks/linux/library/l-cpdecor.html

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
f0b0s
  • 2,978
  • 26
  • 30
1

A decorator, also called pie syntax. It allows you to "decorate" a function with another function. You already had decoration with staticmethod() and classmethod(). The pie syntax makes it more easy to access and extend.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Stefano Borini
  • 138,652
  • 96
  • 297
  • 431
  • from the wiki, during the discussion about the choice. I think it comes from java traditional naming http://wiki.python.org/moin/PythonDecorators#A1.piedecoratorsyntax – Stefano Borini Jun 28 '09 at 00:31
1

If you ask this type of question you will probably be interested in the other hidden features of Python.

Community
  • 1
  • 1
wr.
  • 2,841
  • 1
  • 23
  • 27
1

That specific decorator looks like it comes from Django.

It might help you get a better understanding by reading the Django documentation about that decorator.

Mattias Nilsson
  • 3,639
  • 1
  • 22
  • 29
0

Some resources for decorator: decorator, PEP 318: Decorators for Functions and Methods, PythonDecorators and PythonDecoratorLibrary.

A decorator article on DDJ and another article (blog post).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
sunqiang
  • 6,422
  • 1
  • 32
  • 32