This Python Decorators lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.
A decorator is a function that wraps another function. The @ line above a def is shorthand for replacing that function with the wrapper.
Use a decorator to add one small behaviour, such as shaping the return value, without editing every call.
Example 1: Start here
The wrapper must accept the same arguments as the function it wraps. This wrapper takes none.
def shout(func): # define the function; it runs when you call it
def wrapper(): # define the function; it runs when you call it
return func().upper() # send this value back to the caller
return wrapper # send this value back to the caller
@shout # extra behavior for the next function
def topic(): # define the function; it runs when you call it
return "python" # send this value back to the caller
print(topic())
Example 2: Wrap a function
The decorator replaces greet with inner. The call still looks like greet().
def shout(func): # define the function; it runs when you call it
def inner(): # define the function; it runs when you call it
return func().upper() # send this value back to the caller
return inner # send this value back to the caller
@shout # extra behavior for the next function
def greet(): # define the function; it runs when you call it
return "hello" # send this value back to the caller
print(greet())
Example 3: Print before the call
inner runs first, then it calls the original function.
def log(func): # define the function; it runs when you call it
def inner(name): # define the function; it runs when you call it
print("calling")
return func(name) # send this value back to the caller
return inner # send this value back to the caller
@log # extra behavior for the next function
def greet(name): # define the function; it runs when you call it
return "Hello " + name # send this value back to the caller
print(greet("Asha"))
Example 4: The same idea without @
@shout is a shorter way to write greet = shout(greet).
def shout(func): # define the function; it runs when you call it
def inner(): # define the function; it runs when you call it
return func().upper() # send this value back to the caller
return inner # send this value back to the caller
def greet(): # define the function; it runs when you call it
return "hello" # send this value back to the caller
greet = shout(greet) # one object
print(greet())
