Skip to main content
6 day streak
Skip to lesson
CareerPetalPython field guide
Loading progress...
Course contents
PYTHON FIELD GUIDE

Course contents 72 topics / 15 parts

Full course overviewOriginal coding practice / separate server checks

Essentials first, then internals and engineering trade-offs.

LESSON 30 / ADVANCED LANGUAGE FEATURES

Context managers and deterministic cleanup

Express resource lifetime with with rather than hope.

AdvancedTutorial 14 min core+12 min deep divePython 3.11+ / 2026-10-27
Saved work unavailable

Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.

Before you start

Learners ready to reason about Python internals, resource boundaries and the listed prerequisites.

Explore the connected curriculum and preparation map

Lesson content version 2026-10-27. Suggested core budget: 14 minutes; optional deep dive: 12 more minutes. These are reading/practice estimates, not a timed test.

Suggested preparation and repair routes

If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.

Actual runtime and local-lab boundaries

Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.

Supported snippets run in the browser; temporary files and SQLite data disappear after each run. Models are labelled conceptual, not traces of your edited source. Full operating-system/framework/cloud labs need separate approval.

Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.

YOU WILL BE ABLE TO
  • Explain enter, work, exit
  • Apply a generator-backed context
  • Reason about async resources differ
01

Enter, work, exit

A context manager gives a block an explicit entry and exit. It makes cleanup happen at block exit rather than relying on when an unused object is eventually collected.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Files and other resources should have a visible lifetime. with places the cleanup rule next to the work and covers exceptional exit too. StringIO provides a browser-local model without opening a host path.

Words you will see

Context manager
An object that supports entry and exit around a with block.
Lifetime
The period when a resource is available for use.
Cleanup
Exit work such as closing a stream or releasing a lock.

Separate the name from resource availability

StringIO creates a stream containing note. Inside with, stream.read consumes the text and stream.closed is False. Leaving the block invokes cleanup, so the next closed check is True. The variable stream still refers to the same object.

Reading the closed object raises ValueError, which this example catches specifically to display a stable explanation. with is not a variable-deletion construct and does not make every reference disappear. Returning the stream from such a block would return an already closed resource.

Match ownership to cleanup responsibility

The code that creates a stream usually owns closing it. A function borrowing a caller's stream should not close it unless that ownership transfer is part of the contract. Cleanup is not rollback: text already sent to an external system would not be undone by closing a handle.

For real files, open with an explicit encoding and supported path. Browser Python cannot read arbitrary files on a laptop. This fixture needs no filesystem, network or garbage-collector timing assumption. A try/finally can also express cleanup, but with packages the reusable entry/exit rule.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. with StringIO('note') as stream:

    Create and enter an owned in-memory stream.

  2. print(stream.read())

    Consume its supplied text while it is open.

  3. print(stream.closed)

    The indented occurrence prints False; the unindented occurrence prints True after exit.

  4. except ValueError:

    Handle only the deliberate read-after-close failure.

A context manager defines setup and teardown around a block. Files, locks and transactions are common examples. Cleanup should run when the block succeeds or raises; garbage collection timing is not a reliable resource-lifetime contract.

Conceptual lifetime of the owned StringIO, not a heap trace

Conceptual reasoning steps for the original example, not a live trace of your edited Python.

  1. EnterCreate a readable memory stream and bind stream.
  2. WorkRead the supplied text inside the block.
  3. ExitClose the stream while the variable still names the closed object.
Predict before you run

What is stream.closed after the block?

The block owns a stream lifetimePYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Use an empty resource.

Try: Replace StringIO('note') with StringIO('').

The first print is blank, but the closed-state sequence is unchanged.

Check identity survives exit.

Try: Add print(type(stream).__name__) after the final handler.

It prints StringIO: closure did not delete the object or name.

Before you move on

After a with block closes a stream, can a second variable that aliases it still read it?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

No. Both names refer to the same now-closed object. Another reference does not reopen the resource or postpone with's cleanup.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
02

A generator-backed context

A generator-backed context manager yields once to let the block run. Put cleanup in finally so it also runs when the block raises.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Many resources follow a small acquire/work/release sequence. contextmanager lets a generator express that sequence without a full class. First understand functions, yield and finally; this example only records events rather than acquiring a real external resource.

Words you will see

yield
Pause a generator and supply a value to its caller.
contextmanager
A decorator that adapts a single-yield generator into a context manager.
finally
A block that runs when control leaves its protected try suite.

One pause separates entry from exit

Calling session(events) creates a manager. Entering it starts the generator and appends enter. yield 7 binds value to 7, then pauses while the with body appends 14. Exiting resumes the generator and finally appends exit.

The generator must yield exactly once along a successful entry/exit path. Yielding zero times or a second time is a protocol error. Create a fresh manager for each use rather than trying to re-enter the same generator-backed instance.

Put the release rule on every exit path

An exception in the with body is thrown back at the paused yield. finally still runs, but it does not suppress the exception. A narrow except can intentionally handle a documented failure; catching everything and silently continuing conceals bugs.

try/finally alone is a good choice for a one-off lifetime. A reusable manager is useful when several call sites share the same rule. Neither form automatically rolls back external side effects. Keep cleanup short and preserve the original error context if cleanup can also fail.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. @contextmanager

    Adapt the single-yield generator to the with protocol.

  2. events.append('enter')

    Run entry work before the caller's block.

  3. yield 7

    Supply the block's value and pause.

  4. events.append(value * 2)

    Append 14 inside the block.

  5. events.append('exit')

    Run final cleanup when the block exits.

contextlib.contextmanager turns a single-yield generator into a context manager. Place cleanup in finally. Exceptions from the block reappear at yield; suppress them only when handling that exact failure is the documented purpose.

Predict before you run

Where does 14 appear relative to enter and exit?

Yield control and return to cleanupPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Change the acquired value.

Try: Change yield 7 to yield 3.

The middle event becomes 6; entry and exit order stays the same.

Use the manager twice correctly.

Try: Add a second with session(events) as value: block that appends value.

A fresh context adds enter, 7, exit after the first three events.

Before you move on

If the with body appends 14 and then raises LookupError, does finally append exit?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

Yes. The error returns through yield, finally appends exit, and the unhandled LookupError continues outward. Cleanup is not suppression.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
03

Record cleanup even after a failure

Exceptional exit should clean up before an outer handler observes the failure. A finally block performs cleanup without claiming the failed work succeeded.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

A successful demonstration alone cannot prove a cleanup path covers errors. The original resource program deliberately raises inside the block and records each stage. The events are a conceptual resource model, not an actual file or transaction.

Words you will see

Propagation
An unhandled exception continuing to an enclosing scope.
Suppression
A manager deliberately preventing an exception from continuing.
Exceptional exit
Leaving a block because an exception was raised.

Read the failure path in order

Entry appends open and yields handle. The body appends handle, then raises ValueError. That error reappears at yield, so finally appends close before control reaches the outer except. Only then does handled join the event list.

The manager has no except that consumes the error. The outer handler is therefore necessary for the final print to run. Removing that handler leaves cleanup intact but makes the error visible as an unsuccessful run.

Cleanup does not mean success

A close event does not imply the resource's operation completed, committed or produced output. If cleanup itself raises, Python normally retains exception context, but the final raised exception may be the cleanup error. Design cleanup to preserve useful diagnostics rather than hide the original failure.

For classes, __exit__ can return a truthy value to suppress an error; return False or None to propagate it. Suppress only the exact expected failure the manager is designed to handle. Avoid broad suppression around business logic or a whole import pipeline.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. events.append('open')

    Record entry before the block runs.

  2. events.append(handle)

    Record the yielded value inside the block.

  3. raise ValueError('demo')

    Force the exceptional exit path.

  4. events.append('close')

    Run cleanup before an outer handler.

  5. events.append('handled')

    Record that the propagated ValueError reached the outer scope.

finally records cleanup before the surrounding handler observes the error. The exception is not silently suppressed.

Predict before you run

Which event immediately precedes handled?

Record cleanup even after a failurePYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Use a successful body.

Try: Remove the raise ValueError('demo') line.

The output is open, handle, close; handled is absent because no error reaches except.

Change only the body event.

Try: Append handle.upper() instead of handle.

The middle event becomes HANDLE and cleanup order stays unchanged.

Before you move on

If the outer except is removed, is close still appended before the ValueError escapes?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

Yes. finally runs while unwinding the manager. The program then raises rather than reaching the final print, so cleanup and successful completion remain different facts.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
DETAILED WALKTHROUGH / NOT JUST A SUMMARY

Where this idea earns its place

A resource should have an owner responsible for acquiring and releasing it. Files, locks and transaction scopes are good examples because their lifetime matters even when an operation fails. A context manager makes that lifetime visible around a block rather than relying on all callers to remember cleanup.

Follow the mechanism step by step

The manager enters, the block runs, and exit receives information about how the block ended. Returning a truthy value from __exit__ suppresses an exception. With contextlib.contextmanager, execution reaches a single yield, the block runs, and execution resumes around that yield; finally is a natural place for unconditional release.

Work through a concrete application

Trace the resource example as an event sequence: open, work or failure, close, then the outer handler. Test cleanup before the handler observes the error. For several dynamically acquired resources, ExitStack can register releases and unwind them in reverse acquisition order without deeply nested source.

Failure cases and misleading shortcuts

A context manager that catches every exception and returns success can hide the actual failure. Cleanup can also raise and complicate the original cause. Do not put an arbitrary number of yields into a contextmanager generator or assume a synchronous resource manager can safely await an asynchronous release.

Cost, ownership and alternatives

Holding a lock or transaction for a long block can increase contention and latency. Keep the protected lifetime as small as correctness permits, not simply as small as possible. Async resources need async with and a bounded cancellation/cleanup policy; moving release into __del__ forfeits deterministic timing.

Verify the contract

Test normal exit, a block exception, acquisition failure and cleanup failure. Confirm whether an exception should propagate or be intentionally translated. For cancellation, coordinate a deterministic point rather than sleeping and hoping the task was inside the critical section.

Transfer question: Why is with better than relying on a file object's destructor?

It expresses a deterministic block boundary and closes the file on exceptional exit. Destructor timing depends on references and implementation details, so it cannot reliably enforce prompt release or clearly report cleanup failures.

RECALL BEFORE YOU SCROLL

Can you explain it?

Try from memory. Feedback stays on this page and does not award judged progress.

Does with rely on eventual garbage collection to close a normal file?
TRANSFER THE IDEA

Rebuild: Record cleanup even after a failure

Without copying the worked code, reproduce its observable contract: finally records cleanup before the surrounding handler observes the error. The exception is not silently suppressed. Then change one boundary input and explain the result.

Your practice starterPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

MAKE THE RULE WORK ON NEW INPUTS

Guided practice and transfer

These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. Export useful unsaved work before leaving.

A short function primer before you begin

def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.

return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.

Return a value, do not only print itPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

GUIDED PRACTICE

Guide: define one resource lifetime

Implement a generator-backed manager that records entry and exit.

The contract

  • scope(events) returns a context manager. On successful entry append 'open' and yield the string 'handle' exactly once.
  • Always append 'close' when the body exits, including when it raises. Never suppress the body's exception.
  • The supplied list is an intentional event sink: append only, preserving existing entries. Each call creates an independently usable manager; no real external resources.
Guide: define one resource lifetimePYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Inspect 6 public checks

Transparent local learning checks, not exhaustive or tamper-proof grading.

  1. normal lifetime
    events = []
    with scope(events) as value:
        assert type(value) is str and value == 'handle'
        assert events == ['open']
        events.append(value)
    assert events == ['open', 'handle', 'close']
  2. empty body
    events = []
    with scope(events) as value:
        assert type(value) is str and value == 'handle'
    assert events == ['open', 'close']
  3. error cleanup
    events = []
    try:
        with scope(events) as value:
            assert type(value) is str and value == 'handle'
            raise ValueError('fixture')
    except ValueError:
        events.append('caught')
    assert events == ['open', 'close', 'caught']
  4. preserve exception identity
    events = []
    error = LookupError('fixture')
    try:
        with scope(events) as value:
            assert value == 'handle'
            raise error
    except LookupError as caught:
        assert caught is error
    else:
        raise AssertionError('Must propagate')
    assert events == ['open', 'close']
  5. nested reverse lifetime
    events = []
    with scope(events) as first:
        with scope(events) as second:
            assert type(first) is str and first == second == 'handle'
            events.append('body')
    assert events == ['open', 'open', 'body', 'close', 'close']
  6. append-only sink ownership
    events = ['existing']
    alias = events
    with scope(events) as value:
        assert type(value) is str and value == 'handle'
    assert events is alias and events == ['existing', 'open', 'close']
    other = []
    with scope(other) as value:
        assert value == 'handle'
    assert other == ['open', 'close'] and events == ['existing', 'open', 'close']
    Why does finally matter more than an append after yield?

    The body error is thrown at yield and skips unprotected following code. finally covers normal and exceptional exit. Each manager retains only its sink reference and appends two fixed events.

    GUIDED PRACTICE

    Guide: read without taking ownership

    Read a borrowed stream while restoring its cursor on every exit.

    The contract

    • Input is an open seekable text stream. Read from its current cursor and return the remaining text as str.
    • Restore the original cursor even when read raises; propagate the same error. Never close the borrowed stream.
    • Do not change its contents. Tests use browser-local StringIO-compatible objects; no host paths or hidden shared streams.
    Guide: read without taking ownershipPYTHON 3

    Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

    Preparing the editor controls. Run and editing become available when this page is interactive.

    Browser Python limits

    Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

    Inspect 6 public checks

    Transparent local learning checks, not exhaustive or tamper-proof grading.

    1. full text
      from io import StringIO
      s = StringIO('tea\nbread')
      r = read_borrowed(s)
      assert type(r) is str and r == 'tea\nbread'
      assert s.tell() == 0 and not s.closed
    2. empty stream
      from io import StringIO
      s = StringIO('')
      r = read_borrowed(s)
      assert type(r) is str and r == '' and s.tell() == 0 and not s.closed
    3. nonzero cursor
      from io import StringIO
      s = StringIO('abcdef')
      s.seek(2)
      r = read_borrowed(s)
      assert type(r) is str and r == 'cdef' and s.tell() == 2 and not s.closed
    4. end cursor
      from io import StringIO
      s = StringIO('abc')
      s.seek(3)
      r = read_borrowed(s)
      assert type(r) is str and r == '' and s.tell() == 3 and not s.closed
    5. repeat and contents ownership
      from io import StringIO
      s = StringIO('xx')
      s.seek(1)
      r = read_borrowed(s)
      assert type(r) is str and r == 'x' and read_borrowed(s) == 'x'
      assert s.getvalue() == 'xx' and s.tell() == 1 and not s.closed
    6. error restoration and identity
      from io import StringIO
      probe = StringIO('ok')
      r = read_borrowed(probe)
      assert type(r) is str and r == 'ok' and not probe.closed
      error = ValueError('fixture')
      class Broken(StringIO):
          def read(self):
              self.seek(3)
              raise error
      s = Broken('abcdef')
      s.seek(1)
      try:
          read_borrowed(s)
      except ValueError as caught:
          assert caught is error
      else:
          raise AssertionError('Propagate read error')
      assert s.tell() == 1 and s.getvalue() == 'abcdef' and not s.closed
      Why is with stream incorrect for this contract?

      The caller owns closing the stream. This function owns only temporary cursor movement. Reading n remaining characters takes O(n) time and result text space; restoration belongs in finally.

      TRANSFER / TRY BEFORE OPENING HINTS

      Transfer: acquire a dynamic set of managers

      Change from one lifetime to a runtime-selected sequence of lifetimes.

      The contract

      • Input is a finite iterable of synchronous context managers whose exits do not suppress errors. Enter them in order using ExitStack.
      • Return a fresh list of yielded values in acquisition order, but only after all exits have run in reverse order.
      • On entry failure release previously entered managers and propagate the same error; do not mutate a source list. This abstract event model yields plain strings, not real live handles to use after closure.
      Transfer: acquire a dynamic set of managersPYTHON 3

      Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

      Preparing the editor controls. Run and editing become available when this page is interactive.

      Browser Python limits

      Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

      Inspect 6 public checks

      Transparent local learning checks, not exhaustive or tamper-proof grading.

      1. two resources and reverse exits
        from contextlib import contextmanager
        events = []
        @contextmanager
        def item(name):
            events.append('open ' + name)
            try:
                yield name
            finally:
                events.append('close ' + name)
        r = collect_contexts([item('a'), item('b')])
        assert type(r) is list and r == ['a', 'b'] and all(type(x) is str for x in r)
        assert events == ['open a', 'open b', 'close b', 'close a']
      2. empty fresh lists
        a = collect_contexts([])
        b = collect_contexts([])
        assert type(a) is list and type(b) is list and a == b == [] and a is not b
      3. one-shot repeated values
        from contextlib import nullcontext
        source = iter([nullcontext('x'), nullcontext('x')])
        r = collect_contexts(source)
        assert type(r) is list and r == ['x', 'x'] and list(source) == []
      4. entry failure unwinds
        from contextlib import contextmanager, nullcontext
        r = collect_contexts([nullcontext('ok')])
        assert type(r) is list and r == ['ok']
        events = []
        error = ValueError('entry')
        @contextmanager
        def good():
            events.append('open')
            try:
                yield 'ok'
            finally:
                events.append('close')
        class Bad:
            def __enter__(self):
                events.append('bad')
                raise error
            def __exit__(self, *args):
                events.append('unexpected exit')
        try:
            collect_contexts([good(), Bad()])
        except ValueError as caught:
            assert caught is error
        else:
            raise AssertionError('Propagate entry error')
        assert events == ['open', 'bad', 'close']
      5. source list ownership
        from contextlib import nullcontext
        source = [nullcontext('b'), nullcontext('a')]
        before = source[:]
        r = collect_contexts(source)
        assert type(r) is list and r == ['b', 'a'] and r is not source
        assert source == before and all(a is b for a,b in zip(source, before))
      6. independent result lists
        from contextlib import nullcontext
        a = collect_contexts([nullcontext('v')])
        b = collect_contexts([nullcontext('v')])
        assert type(a) is list and type(b) is list and a == b == ['v'] and a is not b
        a.append('changed')
        assert b == ['v']
        What changed from a single with block?

        A dynamic number of acquisitions needs registered reverse exits, including partial failure. For n managers ExitStack keeps O(n) exit state and the result holds n references. Returning these plain values does not extend any resource lifetime.

        A GOOD PLACE TO PAUSE

        Core route complete.

        If you can explain the checkpoint and attempt the practice, move on. Come back for the deep dive when you want the why behind the how.

        Save your core reading milestone

        Exit semantics

        ExitStack records cleanup operations as resources are acquired, then releases them in reverse order. It is useful when the number of contexts is chosen at runtime.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        A batch may open a variable number of resources, so fixed nested with statements are awkward. ExitStack expresses that dynamic ownership while preserving reverse-order release. This demonstration uses event lists, not host files.

        Words you will see

        ExitStack
        A manager that gathers context exits and cleanup callbacks.
        LIFO
        Last in, first out: reverse order of registration.
        Partial acquisition
        A situation where earlier resources were acquired before a later entry failed.

        Register only what was entered

        enter_context enters item a and records its exit, then does the same for b. The body combines the yielded names as ab. On leaving the stack, b closes first, then a, matching the reverse of their successful entry order.

        If entering a later resource raises, earlier registered exits still run while leaving the stack. The resource whose own entry failed must handle any cleanup required for its incomplete acquisition; its normal exit was not registered by a successful enter_context.

        Callbacks and suppression have different contracts

        ExitStack.callback registers an ordinary cleanup callable; it does not receive exception details or suppress an exception. enter_context registers actual context-manager exit behaviour, which may affect exception propagation. Avoid treating every callback as a transaction rollback.

        For a fixed pair of resources, a normal multi-manager with is often clearer. Use a stack when acquisition is conditional or dynamic. Cleanup still occurs on block exit; it is not deferred until arbitrary collection of the stack object. Costs grow with the number of registered exits.

        The original example, step by step

        These steps explain the original code below. They do not change when you edit your own experiment.

        1. with ExitStack() as stack:

          Establish a scope that owns registered exits.

        2. handles = [stack.enter_context(item(name, events)) for name in ['a', 'b']]

          Enter a then b and save their yielded values.

        3. events.append('use ' + ''.join(handles))

          Use both handles before either is closed.

        4. print(events)

          After scope exit, inspect reverse-order cleanup.

        __exit__ receives exception information; returning a truthy value suppresses it. Cleanup failure can complicate or mask the original failure, so preserve diagnostic context. ExitStack helps manage a variable number of contexts with reverse-order cleanup.

        Predict before you run

        Which item closes first?

        Release in reverse acquisition orderPYTHON 3

        Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

        Preparing the editor controls. Run and editing become available when this page is interactive.

        Browser Python limits

        Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

        Change one thing; explain the difference.

        Add another resource.

        Try: Change the names to ['a', 'b', 'c'].

        The use event becomes use abc, followed by close c, close b, close a.

        Acquire no resources.

        Try: Change the names to [].

        Only use followed by a space is recorded; there are no registered exits.

        Before you move on

        For successful entries x, y and z, in what order does the stack call their exits?

        Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

        Read a worked answer

        z, y, x. Reverse order helps release dependent resources before the resources they may rely on.

        This is a self-check, not a required quiz or a saved score. You can revisit any concept.

        Async resources differ

        An asynchronous context manager can await entry and cleanup. The protocol is different from synchronous with, even when a small demonstration completes without external I/O.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Some resources need asynchronous acquisition or release, such as a connection whose protocol requires an awaited close. async with provides that protocol. Know async def, await and coroutine execution first; synchronous code should usually keep a normal manager.

        Words you will see

        Coroutine
        An asynchronous computation that must be awaited or driven by an event loop.
        async with
        A block that awaits asynchronous context entry and exit.
        Cancellation
        A request to stop an asynchronous task, normally delivered through an exception at an await point.

        Match the manager to its caller

        asynccontextmanager adapts an async single-yield generator. main enters it with async with, appends the yielded ready value, then exit is appended in finally. Calling main creates a coroutine. Because every awaited operation in this fixture completes immediately, one send(None) step runs it to completion and raises StopIteration.

        This intentionally narrow driver uses the coroutine protocol, not an event loop. It is not suitable for real asynchronous I/O: an await that actually suspends would need an appropriate runner. No asyncio loop is created or replaced, making the local demonstration independent of an already-running browser loop.

        Cleanup can itself suspend

        A real async manager may await cleanup. Define cancellation and timeout behaviour deliberately: finally starts cleanup during unwinding, but awaited cleanup is not an unconditional guarantee against all later interruption or process termination. Keep release idempotent where the resource permits it.

        Do not block an event loop with a slow synchronous __enter__ or file operation merely by placing it inside async code. Use the appropriate asynchronous library or an explicit supported execution boundary. For a plain StringIO lifetime, a synchronous with is simpler and sufficient.

        The original example, step by step

        These steps explain the original code below. They do not change when you edit your own experiment.

        1. @asynccontextmanager

          Adapt the asynchronous generator to the async context protocol.

        2. async with session(events) as value:

          Await entry and receive ready.

        3. events.append(value)

          Use the supplied value inside the lifetime.

        4. awaitable.send(None)

          Step this non-suspending coroutine to completion; normal completion raises StopIteration.

        5. awaitable.close()

          Close the demonstration coroutine without touching any host event loop.

        An async context manager uses async with and may await acquisition/cleanup. Do not block an event loop in a synchronous __enter__. Define what cancellation means during cleanup and how long cleanup may take.

        Predict before you run

        When is exit appended?

        Await entry and cleanup without external I/OPYTHON 3

        Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

        Preparing the editor controls. Run and editing become available when this page is interactive.

        Browser Python limits

        Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

        Change one thing; explain the difference.

        Change the acquired value.

        Try: Change yield 'ready' to yield 'open'.

        The middle event becomes open while entry and exit remain in order.

        Observe an empty body.

        Try: Replace events.append(value) inside main with pass.

        The result contains only enter and exit; cleanup still runs.

        Before you move on

        Does writing async def by itself execute the function body when it is called?

        Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

        Read a worked answer

        No. Calling it creates a coroutine. It must be awaited or driven for entry, work and cleanup to occur. Real suspending I/O needs a supported event loop; this fixture's manual single step only works because nothing suspends.

        This is a self-check, not a required quiz or a saved score. You can revisit any concept.

        Make the explanation your own.

        Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.

        Take a versioned study copy

        Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.

        Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.

        REFLECT, THEN CONTINUE

        Make this a milestone.

        Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.

        Your account

        Loading account...

        Sign in to save your work across devices.