Skip to content
Learn Netverks

Lesson

Step 30/36 83% through track

context-managers

Context managers

Last reviewed May 28, 2026 Content v20260528
Track mode
server_script
Means
Server runner
Reading
~1 min
Level
intermediate

This lesson

This lesson teaches Context managers: the syntax, patterns, and safety habits you need before advancing in Python.

Teams still ship Context managers in Python codebases—skipping it leaves gaps in debugging and code reviews.

You will apply Context managers in contexts like: Scripts, Django/FastAPI apps, notebooks, and glue code between systems.

Write Python 3 in the editor and click Run on server—the dev runner executes your script with print() for output; stdlib only in playground snippets (LEARNING_RUNNER_ENABLED=true).

Toward the end of the track—consolidate before capstone-style review lessons.

Context managers guarantee setup and teardown via with—files, locks, and DB connections. Implement with __enter__/__exit__ or the @contextmanager decorator from contextlib.

with statement

with open("data.txt") as f:
    data = f.read()
# file closed here

Custom context manager

from contextlib import contextmanager

@contextmanager
def tag(name):
    print(f"[{name}] start")
    try:
        yield name
    finally:
        print(f"[{name}] end")

Important interview questions and answers

  1. Q: __exit__ and exceptions?
    A: Receives exception info; return True to suppress; otherwise exception propagates after cleanup.
  2. Q: contextmanager vs class?
    A: Decorator suits simple setup/yield/teardown; class fits reusable stateful managers.

Self-check

  1. What keyword uses a context manager?
  2. When is __exit__ called?

Tip: with open(...) is the classic pattern—context managers guarantee cleanup.

Interview prep

__exit__ return True?

Suppresses the exception—use sparingly; usually let exceptions propagate after cleanup.

@contextmanager?

Generator-based manager—code before yield is __enter__, finally after yield is cleanup.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • with statement?
  • Custom __enter__?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump