0Pricing
Python Academy · Lesson

The with Statement in Depth

Understand how with works and why it prevents resource leaks.

Introduction

The with statement guarantees setup and teardown code runs, even when exceptions occur.

Basic with Usage

with expr as var: — expr must return a context manager. var is bound to whatever __enter__ returns.
with open('/tmp/cm_test.txt','w') as f:
    f.write('hello')
print('file closed:', f.closed)

All lessons in this course

  1. The with Statement in Depth
  2. __enter__ and __exit__ Protocol
  3. contextlib: @contextmanager
  4. Practical Context Manager Patterns
← Back to Python Academy