Decorators
Decorators
Sometimes you want to add extra behavior to a function without changing the function itself.
Python gives us decorators for this.
Decorators are common in real Python projects and frameworks.
What Is a Decorator?
A decorator is a function that wraps another function and adds extra behavior.
Examples:
- logging
- timing
- access checks
- validation
- formatting output
Why Decorators Matter
Decorators help you:
- reuse code
- keep functions clean
- separate extra logic
- apply the same behavior to many functions
Functions Are Objects
In Python, functions can be stored in variables and passed to other functions.
def hello():
print("Hello")
greet = hello
greet()
Output
Hello
This is why decorators are possible.
Basic Decorator Example
def decorator(func):
def wrapper():
print("Before")
func()
print("After")
return wrapper
def greet():
print("Hello")
greet = decorator(greet)
greet()
Output
Before
Hello
After
Using @ Syntax
Python gives a cleaner way.
def decorator(func):
def wrapper():
print("Before")
func()
print("After")
return wrapper
@decorator
def greet():
print("Hello")
greet()
Output
Before
Hello
After
Decorator with Arguments
def decorator(func):
def wrapper(name):
print("Start")
func(name)
print("End")
return wrapper
@decorator
def greet(name):
print("Hello", name)
greet("Tom")
Output
Start
Hello Tom
End
Real Example: Simple Logger
def log_call(func):
def wrapper():
print("Function running")
func()
return wrapper
@log_call
def save():
print("Saved")
save()
Output
Function running
Saved
Code Along
Create a decorator that prints:
- Start
- then runs function
- then prints Done
Mini Challenge
Create a decorator named stars.
Tasks:
When used on a function, print:
*****
Hello
*****
Expected output:
*****
Hello
*****
Real World Use Case
Decorators are used in web frameworks, authentication, caching, logging, and testing tools.
Quiz
- What is a decorator?
- Why are decorators useful?
- What does
@decorator_namedo? - Can decorators add behavior before and after a function?
Assignment
Create a decorator that prints Running... before a function executes.
Summary
You learned how decorators wrap functions and add reusable behavior without changing the original function.