External Exam Download Resources Web Applications Games Recycle Bin

Decorators

decorators1.py

def this_is_a_decorator(x): #x is incoming function to wrap
    print("A")
    print(x())
    return "C"

####^^^ HIDDEN BY FLASK ^^^^#####

@this_is_a_decorator
def trigger():
    return "BB"

print(trigger)

decorators2.py

#####WITHOUT SYNTACTIC SUGAR:#####
def no_decorator(x):
    print("A")
    print(x())
    return "C"

def trigger():
    return "BB"

trigger = no_decorator(trigger)

print(trigger)


#####WITH SYNTACTIC SUGAR:#####
def this_is_a_decorator(x): #x is incoming function to wrap
    print("A")
    print(x())
    return "C"

@this_is_a_decorator
def trigger():
    return "BB"

print(trigger)
Decorators are functions which modify the functionality of other functions. They make code shorter and more "Pythonic". They are the things that start with the @ symbol and precede a function call. Decorators are often referred to as "syntactic sugar"... cause all they do is make our code look pretty(er). For example, the following 2 code samples produce identical output:

With decorator:

from flask import *
app = Flask(__name__)

@app.route("/")
def main():
    return "Hello Flask!"
 
app.run()


Without decorator:

from flask import *
app = Flask(__name__)

def main():
    return "Hello Flask!"

main = app.route("/")(main)
 
app.run()