🎓 All Courses | 📚 Python Programming Syllabus

📋 Study this course on TaskLoco
#python-programming#context-managers#advanced

Context Managers — The with Statement

Context managers handle setup and teardown automatically — even if an error occurs.


You already use them:

with open("file.txt") as f:
    content = f.read()
# File is automatically closed here

How it works: The with statement calls __enter__ on entry and __exit__ on exit (even on exceptions).


Custom context manager:

class Timer:
    def __enter__(self):
        import time
        self.start = time.time()
        return self

    def __exit__(self, *args):
        self.elapsed = time.time() - self.start
        print(f"Elapsed: {self.elapsed:.2f}s")

with Timer() as t:
    # do something
    sum(range(1000000))
# Prints elapsed time automatically

Using contextlib:

from contextlib import contextmanager

@contextmanager
def managed_resource():
    print("Setup")
    yield
    print("Teardown")

YouTube • Top 10
Python Programming: Context Managers
Tap to Watch ›
📸
Google Images • Top 10
Python Programming: Context Managers
Tap to View ›

Reference:

Wikipedia: Python Syntax

image for linkhttps://en.wikipedia.org/wiki/Python_syntax_and_semantics

📚 Python Programming — Full Course Syllabus
📋 Study this course on TaskLoco

TaskLoco™ — The Sticky Note GOAT