Python CoreNot Started
Decorators
Functions that wrap other functions — the foundation of Flask routing
0%
Knowledge Debt detected
You can study this freely — but your score may plateau if these foundations have gaps. The Mastery badge requires them to be solid.
Explanation
A is a function that takes another function and extends its behavior without modifying it.
python
def log_calls(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}")
result = func(*args, **kwargs)
print(f"Done")
return result
return wrapper@log_calls def greet(name): return f"Hello, {name}!"
greet("Alice") # Calling greet # Done ```
The @decorator syntax is for greet = log_calls(greet).
This is how Flask routes work:
python @app.route("/home") def home(): return "Hello!"
Examples
Timing decorator
Measure how long a function takes
import time
def timer(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"{func.__name__} took {time.time()-start:.3f}s")
return result
return wrapper
@timer
def slow():
time.sleep(0.1)
slow() # slow took 0.100sNext in Python Core
Comprehensions