12

I am following this Flask tutorial. We declare routes like @app.route('/') , but no variable in python can contain @ character.
I'm confused that what is @app and where it came from. Here's the code snippet :

from app import app

@app.route('/')
@app.route('/index')
def index():
    return "Hello, World!"
DevHugo
  • 129
  • 1
  • 1
  • 12
Satwik
  • 1,281
  • 4
  • 18
  • 31

2 Answers2

24

The @ is telling Python to decorate the function index() with the decorator defined in app.route().

Basically, a decorator is a function that modifies the behaviour of another function. As a toy example, consider this.

def square(func):
    def inner(x):
        return func(x) ** 2
    return inner

@square
def dbl(x):
    return x * 2 

Now - calling dbl(10) will return not 20, as you'd expect but 400 (20**2) instead.

This is a nice step-by-step. explanation of decorators.

Chinmay Kanchi
  • 62,729
  • 22
  • 87
  • 114
  • 2
    This concept is also known as a closure. It's a nice way to add more functionality to a function without having to create a class. – m1yag1 Feb 11 '16 at 15:14
  • 1
    @m1yag1 You just made me finally understand what a closure is useful for, by identification with Python's decorators, thanks ;) – JulienD Feb 11 '16 at 22:50
  • 1
    Why is line 3 `return func(2) ** 2`, should it be `return func(x) ** 2` instead? – Kingsley Dec 21 '18 at 01:03
18

It is a decorator. When decorated by @app.route('/') (which is a function), calling index() becomes the same as calling app.route('/')(index)().

Here is another link that can explain it, in the python wiki.

JulienD
  • 7,102
  • 9
  • 50
  • 84