Skip to main content

Python Tutorial 5.5 - Decorators in Python

Welcome to the “Decorators” tutorial!


Overview

Decorators wrap a function to modify or enhance its behavior.

Syntax

def decorator(fn):
    def wrapper(*args, **kwargs):
        # before
        result = fn(*args, **kwargs)
        # after
        return result
    return wrapper

@decorator
def greet():
    print("Hello!")

Example: Timing Decorator

import time

def timer(fn):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = fn(*args, **kwargs)
        end = time.time()
        print(f"Elapsed: {end - start:.4f}s")
        return result
    return wrapper

@timer
def waste_time(n):
    for _ in range(n):
        pass

waste_time(1000000)

Key Takeaways

  • Use @decorator_name syntax.
  • Decorators receive and return functions.

Happy coding!

Comments