Skip to main content
Loading page…
Python Mastery
Chapter 17
Lesson 3 of 3
Context Managers (with)
Contents
Notes
Tutor
Concept
The with Statement and Why It Exists
Loading activity…
Previous
1 / 9
Continue
Contents
Notes
Discussion
Tutor
28 min
9 activities
0 of 9 done
In this lesson
1
The with Statement and Why It Exists
2
The Protocol: __enter__ and __exit__
3
contextlib.contextmanager — The Easy Way
4
Suppressing Exceptions in __exit__
5
Check: __exit__ Signature
6
Practice: Implement a Reentrant Counter Context Manager
7
Practice: Class-Based Timer Context Manager
8
Context Managers: Knowledge Check
9
Pro Tip: ExitStack for Dynamic Context Managers
Objectives
Explain what a context manager does and why it guarantees cleanup
Implement a context manager class using __enter__ and __exit__
Create a context manager with contextlib.contextmanager
Write a practical timer and temporary-directory context manager
Chapter 17 · Decorators, Closures & Context Managers
Closures & First-Class Functions
Decorators
Context Managers (with)
Previous: Decorators
Next: Type Hints Basics