Lesson 36 / 47
Decorator Basics
A function that wraps another function to add behaviour, without changing its code.
@decorator syntax
A decorator takes a function, returns a new wrapped function. @decorator above a def is shorthand for func = decorator(func).
def shout(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return result.upper()
return wrapper
@shout
def greet(name):
return f"hello, {name}"
print(greet("ada")) # HELLO, ADAWrapping, not changing
A decorator is like gift wrapping — the function inside is unchanged, but it now comes with extra behaviour around it.