What does the "at" (@) symbol do in Python?
@ symbol at the beginning of a line is used for class, function and method decorators.
Read more here:
The most common Python decorators you'll run into are:
If you see an
@ in the middle of a line, that's a different thing, matrix multiplication. See this answer showing the use of
@ as a binary operator.
class Pizza(object): def __init__(self): self.toppings =  def __call__(self, topping): # When using '@instance_of_pizza' before a function definition # the function gets passed onto 'topping'. self.toppings.append(topping()) def __repr__(self): return str(self.toppings)pizza = Pizza()def cheese(): return 'cheese'def sauce(): return 'sauce'print pizza# ['cheese', 'sauce']
This shows that the
class you're defining after a decorator is just basically passed on as an
argument to the
method immediately after the
The microframework Flask introduces decorators from the very beginning in the following format:
from flask import Flaskapp = Flask(__name__)def hello(): return "Hello World!"
This in turn translates to:
rule = "/"view_func = hello# They go as arguments here in 'flask/app.py'def add_url_rule(self, rule, endpoint=None, view_func=None, **options): pass
Realizing this finally allowed me to feel at peace with Flask.
This code snippet:
def decorator(func): return funcdef some_func(): pass
Is equivalent to this code:
def decorator(func): return funcdef some_func(): passsome_func = decorator(some_func)
In the definition of a decorator you can add some modified things that wouldn't be returned by a function normally.