← All Exercises

Custom Context Manager

intermediatepython~20min

Background

Context managers ensure proper resource cleanup even when exceptions occur.

Problem

Create a context manager that handles file or database connections with automatic cleanup.

Input

A resource to manage

Output

Managed resource with cleanup

Sample tests

Sample 1

Input: with ManagedResource() as r
Expected: auto cleanup

Your solution

Learning objective

Learn RAII pattern and resource management in Python