Learn Python · 13/15

Decorators and Context Managers

8 min read

Decorators and Context Managers in Python 🎩

Welcome to the wonderful world of Decorators and Context Managers! These are two powerful, intermediate Python features that, once you get the hang of them, will make your code more elegant, reusable, and robust. They are used everywhere in professional Python code, especially in frameworks like Flask and Django.

Let's demystify these concepts one step at a time.

1. First-Class Functions and Closures

Before you can truly understand decorators, you have to grasp a fundamental concept in Python: functions are first-class objects.

The Problem: Imagine you want to apply an operation (like squaring or cubing) to every number in a list. You could write separate functions for each, but what if you could just pass the operation itself as an argument?

The Solution: First-Class Functions

In Python, functions are not just blocks of code; they are objects, just like strings, lists, or numbers. This means you can:

  • Assign a function to a variable.
  • Store functions in data structures (like a list or dictionary).
  • Pass a function as an argument to another function.
  • Return a function from another function.

Example: Functions as objects

python
def say_hello(name):
  return f"Hello, {name}!"

# 1. Assign to a variable
greet = say_hello
print(greet("freeCodeCamp")) # Output: Hello, freeCodeCamp!

# 2. Pass as an argument
def apply_to_list(func, data_list):
  return [func(item) for item in data_list]

def square(x):
  return x * x

numbers = [1, 2, 3, 4]
squared_numbers = apply_to_list(square, numbers)
print(squared_numbers) # Output: [1, 4, 9, 16]

This ability to pass behavior (the square function) around is the foundation of decorators.


Closures: Functions with Memory 🧠

Now, let's add a little magic. What if a function could "remember" the environment in which it was created?

The Problem: You need to create several similar functions, each one configured with a specific value. For instance, functions that multiply by 2, by 3, and by 10.

The Solution: Closures

A closure is a nested function that remembers the variables from its enclosing (parent) function's scope, even after the parent function has finished executing. Think of it as a function that carries around a little backpack of information from where it was born.

Example: A "multiplier" factory

python
def multiplier_factory(factor):
  # This is the enclosing function
  def multiply(n):
    # The inner function "remembers" the 'factor'
    return n * factor
  
  return multiply

# Create functions from the factory
double = multiplier_factory(2)
triple = multiplier_factory(3)

# Use the new functions
print(double(5))   # Output: 10
print(triple(5))   # Output: 15

Here, double is a closure. Even though multiplier_factory finished running, double still has access to the factor variable (with a value of 2). This "memory" is the secret ingredient that makes decorators work.

2. Creating Simple Decorators

Now that we know about first-class functions and closures, we're ready for the main event!

The Problem: You have several functions, and for each one, you need to log a message before and after it runs. You could add print() statements inside every function, but that's repetitive and clutters your core logic. This violates the DRY (Don't Repeat Yourself) principle.

The Solution: Decorators

A decorator is a function that takes another function as input, adds some functionality to it (without changing the original function's code), and returns the modified function. It's like putting a fancy hat on your function to give it new powers.

Let's build a decorator to solve our logging problem.

Example: A simple logging decorator

python
def log_activity(original_function):
  # The 'wrapper' is a closure that "remembers" original_function
  def wrapper():
    print(f"Executing {original_function.__name__}...")
    original_function()
    print(f"Finished executing {original_function.__name__}.")
  
  return wrapper

def process_data():
  print("Processing some data!")

# The classic way to decorate
decorated_process_data = log_activity(process_data)
decorated_process_data()

# The Pythonic way with "@" syntax
@log_activity
def upload_report():
  print("Uploading a report!")

upload_report()

Output for both calls:

elm
Executing process_data...
Processing some data!
Finished executing process_data.
Executing upload_report...
Uploading a report!
Finished executing upload_report.

The @log_activity syntax is just a cleaner, more readable way of writing upload_report = log_activity(upload_report).

Common Industry Use-Cases:

  • Logging: To record when functions are called and what they return.
  • Timing: To measure how long a function takes to execute.
  • Authentication: In web frameworks, to check if a user is logged in before allowing them to access a specific page.
  • Caching: To store the results of expensive function calls and return the cached result if the same inputs are used again.

3. Decorators with Arguments and functools.wraps

Our simple decorator works, but what about functions that take arguments? And what happens to our original function's identity?

The Problem #1: Our log_activity decorator only works for functions with no arguments. What if we try to decorate def greet(name): ...? It will break!

The Solution: We need to make our wrapper function accept any number of positional or keyword arguments and pass them along to the original function. We do this with *args and **kwargs.

The Problem #2: When you decorate a function, it loses its original metadata (like its name __name__ and its docstring __doc__). It thinks its name is "wrapper". This can be a nightmare for debugging and introspection tools.

The Solution: Python's built-in functools module has a special decorator called @wraps that you apply to your wrapper function. It copies the metadata from the original function to the wrapper, preserving its identity.

Let's upgrade our decorator.

Example: A robust decorator

python
import functools
import time

def timer(func):
  """A decorator that prints the time a function takes to run."""
  @functools.wraps(func) # This is the magic!
  def wrapper(*args, **kwargs):
    start_time = time.perf_counter()
    value = func(*args, **kwargs) # Pass arguments and get return value
    end_time = time.perf_counter()
    run_time = end_time - start_time
    print(f"Finished {func.__name__!r} in {run_time:.4f} secs")
    return value
  
  return wrapper

@timer
def waste_some_time(num_times):
  """A simple function that loops a number of times."""
  for _ in range(num_times):
    sum(i**2 for i in range(10000))

# The decorated function works with arguments
waste_some_time(1)
waste_some_time(999)

# And its identity is preserved!
print(waste_some_time.__name__)
print(waste_some_time.__doc__)

Output:

livecodeserver
Finished 'waste_some_time' in 0.0034 secs
Finished 'waste_some_time' in 3.3987 secs
waste_some_time
A simple function that loops a number of times.

4. Writing Custom Context Managers

Let's switch gears to another powerful concept that helps manage resources cleanly.

The Problem: You are working with a resource that needs to be explicitly opened and closed, like a file or a database connection. What happens if an error occurs after you've opened the resource but before you close it? The program might crash, leaving the resource open, which can lead to data corruption or resource leaks.

You could use a try...finally block every time, but that's verbose.

python
# The verbose way
file = open("hello.txt", "w")
try:
  file.write("Hello, World!")
except SomeError:
  print("An error occurred!")
finally:
  # This block always runs, ensuring the file is closed.
  file.close()

The Solution: Context Managers and the with statement

A context manager is an object designed to be used with the with statement. It automates the setup and teardown of resources, guaranteeing that the cleanup code (like file.close()) is always executed, even if errors occur.

python
# The clean, context manager way
with open("hello.txt", "w") as file:
  file.write("Hello, World!")
# The file is automatically closed here!

Python provides two main ways to create your own context managers.

Method 1: The Class-Based Approach

You can create a class with two special methods: __enter__ and __exit__.

  • __enter__: Sets up the resource and is called at the start of the with block. Its return value is assigned to the variable after as.
  • __exit__: Cleans up the resource and is called when the with block is exited (either normally or due to an error).

Example: A Database Connection Manager

python
import sqlite3

class DatabaseConnection:
  def __init__(self, db_name):
    self.db_name = db_name
    self.conn = None

  def __enter__(self):
    print(f"Connecting to {self.db_name}...")
    self.conn = sqlite3.connect(self.db_name)
    return self.conn.cursor()

  def __exit__(self, exc_type, exc_val, exc_tb):
    # exc_type, exc_val, exc_tb contain exception info if one occurred
    if self.conn:
      self.conn.commit()
      self.conn.close()
      print(f"Connection to {self.db_name} closed.")

with DatabaseConnection("test.db") as cursor:
  cursor.execute("CREATE TABLE IF NOT EXISTS users (name TEXT, age INTEGER)")
  cursor.execute("INSERT INTO users VALUES ('Alice', 30)")

Method 2: The contextlib Decorator Approach

For simpler cases, writing a full class can feel like overkill. The contextlib module provides an @contextmanager decorator that lets you create a context manager from a simple generator function. This is often more concise and readable.

The code before the yield statement is the setup (__enter__) and the code after is the teardown (__exit__).

Example: A Simple Timer Context Manager

python
from contextlib import contextmanager
import time

@contextmanager
def simple_timer():
  """A context manager to time a block of code."""
  try:
    start_time = time.perf_counter()
    # The 'yield' passes control to the 'with' block
    yield
  finally:
    # This code runs after the 'with' block is done
    end_time = time.perf_counter()
    elapsed = end_time - start_time
    print(f"Block executed in {elapsed:.4f} seconds.")

with simple_timer():
  # This code will be timed
  total = sum(i for i in range(1000000))
  print("Calculation complete.")

# Output:
# Calculation complete.
# Block executed in 0.0521 seconds.

This approach is highly favored in the industry for its simplicity and elegance when managing straightforward resources.


📚 Extra Reading

Challenge

Challenge: Advanced Performance Logging with a Custom Context Manager

You are tasked with building a sophisticated logging utility that combines the power of decorators and context managers. This utility will time the execution of functions and log the performance data using a controlled resource manager.

Part 1: The Context Manager

  1. Create a class-based context manager named LogFile.
  2. The __init__ method should accept a filename string.
  3. The __enter__ method should print the message Opening log file: {filename} and return a simple logging function. This returned function should accept a single string argument and print it to the console.
  4. The __exit__ method should handle the standard exc_type, exc_val, exc_tb arguments and print the message Closing log file: {filename}, regardless of whether an exception occurred.

Part 2: The Decorator

  1. Create a decorator named performance_logger.
  2. This decorator must be configurable, accepting an optional string argument log_file which defaults to 'performance.log'.
  3. Inside the decorator, use your LogFile context manager to manage the logging process. The log_file argument from the decorator should be passed to the LogFile context manager.
  4. The wrapper function within the decorator must:
    • Accept arbitrary positional and keyword arguments (*args, **kwargs).
    • Record the time before and after the decorated function is executed.
    • Calculate the execution duration.
    • Use the logging function provided by the LogFile context manager's __enter__ method to log a message in the format: Function '{function_name}' executed in {duration:.4f}s.
    • Return the result of the original decorated function.
  5. Crucially, you must use @functools.wraps on your wrapper function to preserve the metadata (like __name__ and __doc__) of the function being decorated.

Expected result

Your final code should contain a complete and correct implementation of both the LogFile class and the performance_logger decorator that satisfy all the requirements from the instructions.

  1. LogFile Class: A class definition with __init__, __enter__, and __exit__ methods implemented as specified.
  2. performance_logger Decorator:
    • A decorator factory function that accepts the log_file argument.
    • The implementation must use a with statement instantiating the LogFile context manager.
    • The wrapper function within the decorator correctly handles *args and **kwargs, times the original function, logs the performance, and returns the original function's result.
    • The wrapper function is correctly decorated with @functools.wraps.

The decorated functions process_data and calculate_complex_stuff should remain untouched at the end of the script.

python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.