02 / MAKE EXECUTION DEPENDABLE · LESSON 07

Close resources when work stops

Use a context manager to release a probe on success, failure or cancellation.

15 min · learn at your pace

Resource lifetime is part of correctness

A socket, file or adapter session can outlive the successful path through a function. If cleanup is only the final statement, an exception can bypass it. A context manager places release behavior beside acquisition and guarantees that the finally block runs when control leaves the with statement.

This lesson's resource is a callable teaching object with close(). Its factory may fail before returning a resource. Acquire it before entering the try block: there is nothing to close if construction never succeeded. Once acquired, close exactly once whether probing succeeds, raises an ordinary error or is interrupted.

Cancellation has a useful boundary

The cancellation callback is checked before each endpoint. Return the rows that finished before it became true; never start another probe after cancellation is observed. A blocking probe must itself honor its timeout, because the caller cannot check a callback while that synchronous operation is still executing.

Do not suppress the original error just to return a partial success. Let an exception propagate after cleanup. The same applies to KeyboardInterrupt. This exercise assumes close succeeds; in a production resource wrapper, decide separately how a cleanup error should be reported without concealing the original failure.

The browser examples use a lightweight resource so behavior is deterministic. The optional local scanner applies the same with-statement idea to actual socket objects. A clean lifetime boundary makes both adapters easier to reason about and prevents abandoned work from retaining handles unnecessarily.

Try an example.py
from contextlib import contextmanager
@contextmanager
def resource():
    try:
        yield "acquired"
    finally:
        print("released")
with resource() as value:
    print(value)
YOUR TURN

Put it into practice.

Implement managed_probe(factory) as a context manager: acquire once, yield the resource, close exactly once when leaving, and propagate exceptions. A failed factory has no resource to close. Define scan_session(factory, endpoints, timeout_ms=500, cancelled=lambda:False). Inputs are already validated endpoint rows. Acquire once, check cancelled() before each probe, append the raw probe(address, port, timeout_ms) results in order, stop consuming after cancellation, and return completed rows. Probe errors and KeyboardInterrupt must escape after cleanup. Assume close() succeeds.

See an explained solution
One way to solve it.py
from contextlib import contextmanager

@contextmanager
def managed_probe(factory):
    resource=factory()
    try:
        yield resource
    finally:
        resource.close()

def scan_session(factory, endpoints, timeout_ms=500, cancelled=lambda:False):
    rows=[]
    with managed_probe(factory) as probe:
        iterator=iter(endpoints)
        while not cancelled():
            try:endpoint=next(iterator)
            except StopIteration:break
            rows.append(probe(endpoint["address"],endpoint["port"],timeout_ms))
    return rows

if __name__ == "__main__":
    class DemoProbe:
        def __call__(self, address, port, timeout_ms):return {"port":port,"state":"open"}
        def close(self):print("Probe closed")
    print(scan_session(DemoProbe, [{"address":"192.0.2.10","port":443}]))

Acquisition and cleanup form one visible lifetime. The loop preserves finished results only for cooperative cancellation, while real failures keep their original exception semantics.