Context Managers
Part of the Python course
Welcome back. Ever since lesson 09 you have been writing with open(...) as f: and trusting that the file gets closed when the block ends. This lesson opens that box. You will learn what the with statement actually does, and how to write your own context managers so any setup-and-teardown pair you have can ride on the same syntax.
Open main.py in the editor. The file uses a small context manager called timer to measure how long a block of code takes, then prints it. Click the play button. You should see something close to:
Want to learn Python Context Managers in a real environment?
Click below, get a fresh Linux box with Python ready to go, and work through Context Managers hands-on with an AI tutor that knows your code.
Start this lessonContext ManagersWhat you'll learn
- With statement
- __enter__ and __exit__
- Writing your own context manager
- Contextlib.contextmanager
Read this lesson in your language
All lessons in this course
19 lessons- 1Hello, Python20 min
- 2Numbers and Strings25 min
- 3Asking the User a Question15 min
- 4Control Flow30 min
- 5Lists and Tuples30 min
- 6Dictionaries and Sets30 min
- 7Functions30 min
- 8Comprehensions25 min
- 9Files and IO30 min
- 10Modules and Packages30 min
- 11Classes and OOP35 min
- 12Inheritance and Composition30 min
- 13Exception Handling30 min
- 14Iterators and Generators30 min
- 15Decorators30 min
- 16Context Managers25 min
- 17Concurrency: Threads and Async40 min
- 18Testing with pytest35 min
- 19Packaging and Deployment35 min
