Skip to main content

08. Function Decorators

Decorators allow you to modify or extend the behavior of functions without changing their code.


A Simple Decorator

def decorator(func):
def wrapper():
print("Before function")
func()
print("After function")
return wrapper

@decorator
def say_hello():
print("Hello")

say_hello()

Passing Arguments

def decorator(func):
def wrapper(*args, **kwargs):
print("Start")
result = func(*args, **kwargs)
print("End")
return result
return wrapper

Practice Challenge

Write a decorator that logs the arguments and return value of a function.


Wrap-Up

  • Use @decorator syntax to apply a decorator.
  • Decorators enable clean separation of concerns.