Context Managers and Descriptors: Resource Control

Learning Objectives: After this lesson, you'll master the with statement, build custom context managers using both classes and contextlib, understand the descriptor protocol, and apply these patterns to manage resources safely.

Context Manager Lifecycle

Before diving into code, let's visualize the complete lifecycle of a context manager:

Loading tool...

The key guarantee: __exit__ is ALWAYS called, even if an exception occurs in the body. This is what makes context managers safe for resource management.

Context Managers: The with Statement

Context managers ensure proper resource acquisition and cleanup, even when exceptions occur.

Why Context Managers Matter

Loading tool...
Loading tool...

The Context Manager Protocol

Loading tool...
Loading tool...

Building Practical Context Managers

Loading tool...

Exception Handling in Context Managers

Loading tool...

contextlib: Simplified Context Managers

The contextlib module provides tools for creating context managers without writing classes.

@contextmanager Decorator

Loading tool...
Loading tool...

Useful contextlib Utilities

Loading tool...

Building Reusable Context Managers

Loading tool...

Descriptors: The Attribute Protocol

Descriptors control what happens when attributes are accessed, set, or deleted.

Loading tool...

Understanding Descriptors

Loading tool...

Data vs Non-Data Descriptors

Loading tool...
Loading tool...

Practical Descriptor: Validated Attribute

Loading tool...

Descriptor: Lazy Property

Loading tool...

How Python Uses Descriptors

Loading tool...
Loading tool...

Combining Context Managers and Descriptors

Loading tool...

Practice Exercises

Exercise 1: Database Transaction Context Manager

Loading tool...

Exercise 2: Type-Checked Descriptor with Conversion

Loading tool...

Key Takeaways

ConceptDescription
Context ManagerObject with __enter__ and __exit__ for resource management
@contextmanagerCreate context managers from generators
ExitStackManage dynamic number of context managers
DescriptorObject with __get__, __set__, __delete__
Data DescriptorHas __set__ or __delete__ - takes precedence over instance dict
Non-Data DescriptorOnly __get__ - instance dict takes precedence

When to Use What

PatternUse Case
Context ManagerResource cleanup, temporary state changes, transactions
@contextmanagerSimple context managers without complex state
DescriptorReusable attribute validation, lazy properties, managed attributes
propertyOne-off computed or validated attributes

Next Steps

In the next lesson, we'll explore Type Hints and Static Typing—learn type annotations, generics, Protocol, and how to use mypy for catching errors before runtime.


Ready for type-safe Python? Type hints await!