PYTHON ADVANCED: PROFESSIONAL ENGINEERING MASTERY / L03CONTEXT MANAGERS AND DESCRIPTORS: RESOURCE CONTROL
课程 · 12 · 03 / 12
LESSON 03 · ADVANCED · 50 MIN · ◆ 2 INSTRUMENTS

Context Managers and Descriptors: Resource Control

Master the with statement, build custom context managers with __enter__/__exit__ and contextlib, and understand the descriptor protocol.

TIP

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:

FIG. 02Flow Diagram
INTERACTIVE
LOADING INSTRUMENT
Fig. 02Interactive flow diagrams, timelines, and process visualizations

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

FIG. 04Flow Diagram
INTERACTIVE
LOADING INSTRUMENT
Fig. 04Interactive flow diagrams, timelines, and process visualizations
FIG. 06Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 06Interactive Python code execution environment

The Context Manager Protocol

FIG. 08Flow Diagram
INTERACTIVE
LOADING INSTRUMENT
Fig. 08Interactive flow diagrams, timelines, and process visualizations
FIG. 10Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 10Interactive Python code execution environment

Building Practical Context Managers

FIG. 12Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 12Interactive Python code execution environment

Exception Handling in Context Managers

FIG. 14Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 14Interactive Python code execution environment

contextlib: Simplified Context Managers

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

@contextmanager Decorator

FIG. 16Flow Diagram
INTERACTIVE
LOADING INSTRUMENT
Fig. 16Interactive flow diagrams, timelines, and process visualizations
FIG. 18Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 18Interactive Python code execution environment

Useful contextlib Utilities

FIG. 20Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 20Interactive Python code execution environment

Building Reusable Context Managers

FIG. 22Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 22Interactive Python code execution environment

Descriptors: The Attribute Protocol

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

FIG. 24Flow Diagram
INTERACTIVE
LOADING INSTRUMENT
Fig. 24Interactive flow diagrams, timelines, and process visualizations

Understanding Descriptors

FIG. 26Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 26Interactive Python code execution environment

Data vs Non-Data Descriptors

FIG. 28Flow Diagram
INTERACTIVE
LOADING INSTRUMENT
Fig. 28Interactive flow diagrams, timelines, and process visualizations
FIG. 30Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 30Interactive Python code execution environment

Practical Descriptor: Validated Attribute

FIG. 32Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 32Interactive Python code execution environment

Descriptor: Lazy Property

FIG. 34Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 34Interactive Python code execution environment

How Python Uses Descriptors

FIG. 36Flow Diagram
INTERACTIVE
LOADING INSTRUMENT
Fig. 36Interactive flow diagrams, timelines, and process visualizations
FIG. 38Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 38Interactive Python code execution environment

Combining Context Managers and Descriptors

FIG. 40Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 40Interactive Python code execution environment

Practice Exercises

Exercise 1: Database Transaction Context Manager

FIG. 42Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 42Interactive Python code execution environment

Exercise 2: Type-Checked Descriptor with Conversion

FIG. 44Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 44Interactive Python code execution environment

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!


Further Reading

Official Docs

Tutorials

Production Patterns

Books

  • Book: Fluent Python (2nd ed.) — Chapter 18 ("with, match, and else Blocks") and Chapter 23 ("Attribute Descriptors"). Both definitive.
  • Book: Effective Python — Items 66–68 on descriptors and metaclasses.