A script that returns the right number can still leave files open, close a stream that belongs to its caller, or hide the error that stopped the work. Those problems often appear only after a second resource fails to open or a cleanup operation raises. Asking DeepSeek to “add a with statement” is too vague to resolve them. A useful review starts with ownership, acquisition order and the evidence that should survive a failure.
This guide uses a small fictional batch of inventory-count files to make resource lifetimes visible. Some inputs are paths that the function must open and close. Other inputs are existing text streams supplied by a caller who retains ownership. We will describe the contract, examine an original standard-library implementation, and test what happens during acquisition, processing and cleanup. The same review questions are useful for more complex resource APIs, but their transaction and lifetime rules must be checked separately.
No live DeepSeek model call or model-quality benchmark was performed for this article. The prompts are reusable review instructions, and the code was developed and tested locally. The exercise covers synchronous Python text streams in a controlled environment. It does not certify arbitrary third-party context managers, asynchronous cancellation, concurrent access, process crashes or operating-system resource limits. The distinction matters because passing a local cleanup test is evidence about that test’s observable behavior, not a universal reliability guarantee.
Write the ownership contract
Imagine a warehouse-training tool that adds integer counts from several fictional text sources. One file might contain counts for blue bins, another for green bins, and an in-memory stream might hold adjustments supplied by a test. These are deliberately unimportant data. The exercise should reveal control flow without requiring production files, customer records, access tokens or an actual warehouse connection. A temporary directory is sufficient for every file-based example.
The caller provides an ordered iterable of sources. A string or path-like object names a text file that the helper opens in UTF-8 read mode. A supplied text stream is borrowed. The helper consumes each source from its current position, strips surrounding whitespace from each line, ignores empty lines, and converts each remaining line with Python’s base-ten integer conversion. It returns the sum only after all its owned resources have completed their cleanup successfully.
That conversion rule is intentionally Python-specific. It is not a business validation policy for stock counts: negative adjustments and any textual form accepted by the chosen conversion are permitted. If your application requires nonnegative ASCII digits, a maximum count or a fixed record grammar, define and test those rules separately. Changing the parser while reviewing cleanup would combine two independent behavior changes and make a failed regression harder to interpret.
State the ownership promise in caller-facing language: resources opened by the helper receive a close attempt when its operation leaves scope; successful close releases them, while streams supplied by the caller remain open. Reading a borrowed stream still advances its position. Ownership preservation therefore does not imply that the object is unchanged. The caller must decide whether it wants to rewind, reuse or close that stream after the helper returns or raises.
Our requirements-analysis guide explains how to turn a broad request into traceable acceptance criteria. Here the most useful criteria describe visible state after each exit path: which streams are closed, which remain usable, whether a result is returned, and which exception reaches the caller. Write those outcomes before asking for a cleaner implementation.
Map acquisition, work and cleanup
Draw three regions on a page. Acquisition turns source descriptions into usable streams. Processing reads records and computes a total. Cleanup releases the resources the operation owns. In the lab, every input is acquired before processing begins. That makes partial-acquisition failures easy to study: if opening the third path fails, the first two owned streams must be released even though no counting work has started.
This all-inputs-open design is a teaching choice rather than a scalability recommendation. Its peak number of open files grows with the input count. A production job that can process files independently will often use a shorter per-file scope instead. Do not ask the model to optimize that choice invisibly: opening all sources first can change when errors occur, while processing one source at a time can consume earlier inputs before discovering that a later path is missing.
The close order in the lab is the reverse of successful acquisition order. If A, B and C were opened, C closes before B and A. If opening C failed, there is no successfully acquired C to close; B and A still need cleanup. Treat each successful acquisition as adding an obligation. A failure while acquiring the next input does not erase obligations already created.
A cleanup diagram should also show what it cannot promise. Closing input streams does not restore their positions, undo parsing already performed, reverse network requests or roll back a database transaction. The helper calculates a local total and does not publish partial output. That limited behavior lets us discuss cleanup precisely without pretending that resource release is a general undo mechanism.

Give DeepSeek a precise review prompt
Give DeepSeek the contract and ask for an exit-path analysis before requesting code. A model can produce a compact refactor that accidentally broadens exception suppression or changes ownership. Asking it to list successful acquisition, later acquisition failure, malformed input and cleanup failure makes those possibilities reviewable. Require it to distinguish the helper’s assumptions from properties guaranteed by the language or library.
Keep the prompt’s evidence small and synthetic. Include two valid input examples, one malformed line, a borrowed stream and the expected close order. The model does not need your real filesystem layout to reason about this boundary. If the existing code contains sensitive paths or application data, replace them consistently while retaining the ownership and exception relationships that matter to the review.
Review a synchronous Python batch-count helper using the standard library.
Inputs are path strings, path-like objects, or caller-owned text streams.
The helper owns only streams it opens itself, using UTF-8 text read mode.
Acquire every source before reading; release owned streams in reverse order.
Borrowed streams remain open, but reading advances their current positions.
Ignore blank lines; convert other stripped lines with int(text, 10).
Do not suppress acquisition, parsing, iteration or cleanup failures.
Explain what happens if opening a later source fails.
Explain what happens if close() raises during another exception.
Propose tests retaining stream references so closure is observable.
Use temporary fictional files. Do not execute model-generated shell commands.
Return a small implementation, a failure matrix and stated limitations.
Do not claim the code has been executed unless execution evidence is supplied.
The final instruction guards against a common review mistake: treating fluent language about tests as a test run. Save the proposed implementation, execute the checks in a disposable environment, and compare actual output with a separately written expectation. Ask the model to explain any discrepancy using the failure log. The useful artifact is the reproducible test and its outcome, not an unsupported assurance that cleanup is safe.
For a second pass, narrow the task further. Ask which exact statement transfers ownership, whether a borrowed stream passes through an unintended context manager, and whether a cleanup exception can alter the caller-visible outcome. Specific questions make it easier to identify a wrong answer. A broad request for “production-ready error handling” invites assumptions that the original contract never authorized.
Build the owned-resource boundary
The lab’s owned_text helper provides the smallest meaningful resource boundary. It opens one path, yields the resulting stream for use, and places close in a finally block. It also records successful open and close events in a simple list. Those events support the teaching trace; the retained stream objects provide separate evidence of actual closure. An event message alone would be an inadequate test of the resource state.
Python’s context-manager protocol distinguishes entering a context from leaving one. The with statement invokes the exit operation after a successful enter when the body finishes, including an exceptional finish. A manager whose own entry fails must handle resources it acquired internally before that failure; the body was never reached. That is why a wrapper’s acquisition sequence deserves review even when the surrounding code already contains with.
The generator-based helper keeps the interesting region explicit: acquisition occurs before yield, the caller’s work happens while execution is suspended at yield, and release is in finally. There is no broad catch-and-continue branch. The body exception normally propagates after cleanup. If closing itself raises, that later failure can become the exception observed by the caller, with the earlier error retained through Python’s exception context.
Keep diagnostic code proportionate to its purpose. The lab passes an ordinary list for events and assumes recording into it works. A production logging sink may block, raise or expose private information. If cleanup must work despite logging failure, logging becomes another failure boundary to design and test. Do not promote a teaching trace into a durable audit record merely by changing its variable name.
Handle a variable number of inputs
The total_from_sources function uses ExitStack to compose the lifetimes selected by the input iterable. Each owned helper is entered as the loop reaches its path. Each borrowed stream is wrapped with nullcontext. The stack unwinds registered exits in reverse order when its surrounding scope ends. That removes the need for a hand-maintained list of close calls spread across several exception handlers.
Registration timing is important. Consider a tempting refactor that opens every path into a list and only afterward arranges cleanup. If one open fails during list construction, the later cleanup region may never be established for the already-open files. The lab enters each ownership boundary immediately rather than accumulating unprotected acquisitions. Ask a reviewer to point at the registration that covers each successfully returned stream.
ExitStack does not discover unrelated resources or close everything reachable from a function. It manages the operations registered with it. In this implementation, every internally opened stream is associated with one entered helper. If a future change creates another resource inside a parsing function, that resource needs its own lifetime decision. A test that currently passes for three files cannot cover a new hidden acquisition automatically.
The source iterable itself can fail while producing its next item. That is different from an input file failing to open, but the earlier ownership obligations still exist. A useful test yields two sources and then raises from the iterable. The expected trace contains cleanup for the two successfully acquired owned streams. This case catches code that reasons only about a final materialized list and overlooks the work done while constructing it.
Respect borrowed streams
A borrowed stream is already inside someone else’s lifetime. It may be an in-memory test fixture, a file opened by a larger workflow or a wrapper whose close method affects another component. Entering that stream directly as a context manager can close it when the helper finishes. The lab uses nullcontext to pass it through without adding a close obligation.
Test this promise on both the success and failure paths. After a successful count, verify the borrowed stream remains open and check where its cursor ended. After malformed input raises, verify it is still open and can be inspected or repositioned by the caller. A test that checks only closed is incomplete if the caller also depends on the documented consumption behavior.
Mix owned and borrowed inputs in the same sequence. For example, place a borrowed adjustment stream between two paths. The returned total includes all three inputs, while cleanup covers only the two paths. This mixed case is more valuable than testing each branch in isolation because a careless refactor may construct one combined list and close every member indiscriminately.
Do not infer ownership from the presence of a close method. Many borrowed objects have one, and an owned resource might require a more specific release operation. Ownership comes from the public contract and the act of acquisition. If an API later needs a transfer-of-ownership option, make that transfer explicit in its name, documentation and tests instead of guessing from object shape.

Run the complete offline lab
Download the complete resource-cleanup lab (ZIP). The complete lab includes the implementation, walkthrough, author tests, independent tests and reproducibility notes. Extract it into a disposable directory. It uses the Python standard library and creates only fictional temporary inputs. Run the commands from its README using an interpreter installed on your machine, and read a failing test before adapting the example to a real workflow.
The public entry point is total_from_sources(sources, *, events, opener=open). The injectable opener makes acquisition and close failures controllable without editing production paths or requiring a failing disk. Its default remains the ordinary file opener. Test doubles must preserve the relevant behavior being checked, and actual temporary-file tests complement those doubles by exercising real text streams.
The implementation is intentionally compact. Review the ownership branch, then locate the stack scope around the acquisition loop and the parsing loop. Notice that the return value reaches the caller only after scope exit. A computation may finish numerically, yet cleanup can still prevent the call from returning successfully. That is part of the stated contract, not a surprising test failure to suppress.
"""Synchronous, offline ownership lab; this is not a production file processor."""
from collections.abc import Callable, Iterable, Iterator
from contextlib import ExitStack, contextmanager, nullcontext
from os import PathLike
from typing import TextIO
Path = str | PathLike[str]
Source = Path | TextIO
Opener = Callable[..., TextIO]
@contextmanager
def owned_text(
path: Path, events: list[str], opener: Opener = open
) -> Iterator[TextIO]:
"""Own one newly opened stream; log successful acquisition and closure."""
stream = opener(path, "r", encoding="utf-8")
try:
events.append(f"open:{path}")
yield stream
finally:
stream.close()
events.append(f"close:{path}")
def total_from_sources(
sources: Iterable[Source], *, events: list[str], opener: Opener = open
) -> int:
"""Sum nonblank integer lines; supplied streams remain caller-owned.
Acquire all sources before reading. Read borrowed streams from their current
positions without rewinding. Parsing uses Python's int(text, 10) semantics.
Processing errors propagate if cleanup succeeds; cleanup may itself raise.
"""
with ExitStack() as stack:
streams = []
for source in sources:
manager = (
owned_text(source, events, opener)
if isinstance(source, (str, PathLike))
else nullcontext(source)
)
streams.append(stack.enter_context(manager))
return sum(
int(line.strip(), 10)
for stream in streams
for line in stream
if line.strip()
)
The walkthrough makes the common path concrete. Its in-memory fixtures stand in for fictional input files, and its borrowed stream supplies another count. Real temporary-file cases are included in the test suite. The expected output reports the total, the acquisition and cleanup trace, and whether the caller’s stream remains open. Read that output against the control flow instead of memorizing it. Changing the order of sources should change the trace predictably without changing an order-independent sum.
"""Three deterministic demonstrations using fictional, in-memory inputs."""
from io import StringIO
from resource_cleanup import total_from_sources
def fictional_open(path, mode, *, encoding):
if mode != "r" or encoding != "utf-8":
raise ValueError("this fixture only supports UTF-8 text reads")
contents = {"north.txt": "10\n20\n", "south.txt": "5\n", "bad.txt": "oops\n"}
try:
return StringIO(contents[str(path)])
except KeyError:
raise FileNotFoundError(str(path)) from None
def main():
events = []
with StringIO("7\n") as borrowed:
total = total_from_sources(
["north.txt", borrowed, "south.txt"],
events=events,
opener=fictional_open,
)
print(f"success total: {total}")
print(f"borrowed still open: {not borrowed.closed}")
print("events:", " -> ".join(events))
for label, sources in [
("acquisition failure", ["north.txt", "missing.txt"]),
("processing failure", ["north.txt", "bad.txt"]),
]:
events = []
try:
total_from_sources(sources, events=events, opener=fictional_open)
except (FileNotFoundError, ValueError) as error:
print(f"{label}: {type(error).__name__}")
print("events:", " -> ".join(events))
if __name__ == "__main__":
main()
Do not run generated code against important inputs merely because this lab passes. Read the code, use isolated fixtures and review its dependencies and side effects first. When adapting it, retain an unchanged baseline run and add a focused test for each new behavior. That gives you a concrete comparison when a later model-assisted revision appears shorter but subtly changes the lifetime contract.
Inject failures at the boundaries
Start with acquisition failure. Configure the test opener to return a real or observable stream for the first path and raise for the second. Keep a reference to the first stream outside the helper. After the call raises, check that reference’s closed state and the recorded order. Confirm that the processing stage never consumed the first stream in this all-inputs-first design.
Next, test processing failure after successful acquisition. Put an invalid integer line in a source and ensure another owned source has already been opened. The call should raise while the stack still closes both owned streams. Include a borrowed source in another version of this case and verify it remains open. This tests two obligations at once: owned cleanup and preserved caller ownership.
Then make iteration itself fail. A custom text-like stream can raise after yielding a valid line. That tests a different branch from integer conversion failure, because the exception arises while requesting the next record. The helper should not return a partial sum. Keep the test’s custom behavior minimal so that a failure identifies the intended boundary rather than a complicated fake implementation.
Finally, inject a close failure. A realistic test can close its underlying in-memory stream and then raise a named exception, making the difference between attempted cleanup, released state and reported failure explicit. Assert that earlier registered cleanup still runs. Also inspect exception chaining when processing had already failed. A close operation that raises before releasing its own resource may leave that resource open; the stack cannot guarantee that a failed cleanup actually released it. A single assertion that “some exception occurred” would miss most of this case’s value.
Our synthetic test-data guide covers the importance of fixtures with known expected outcomes. For cleanup tests, the strongest fixtures expose lifetime state and event order directly. Randomizing many numeric inputs is less helpful than deliberately failing one acquisition or close operation at the boundary where the contract could break.
Keep exception meaning visible
Exception handling is a policy decision. Returning zero after every error would make a missing input indistinguishable from a legitimate total of zero. Logging a parsing error and continuing would turn complete-batch semantics into partial-batch semantics. Suppressing close failures might be acceptable for a particular application, but it would change this lab’s promise and require a documented caller-visible alternative.
Keep ordinary cleanup and business recovery separate in the review. A failed parse tells the caller that the batch did not produce an accepted total. Closing a file handles the resource lifetime. Neither step decides whether to retry, quarantine the input or notify an operator. Those decisions depend on the surrounding workflow and should not be smuggled into a small resource-management refactor.
Be especially careful with a return inside finally. Python’s control-flow rules allow such a return to discard an exception that would otherwise propagate. A manager that catches a body exception and fails to re-raise it can likewise change failure into apparent success. Ask the model to identify these exact constructs and explain a concrete failing example rather than merely recommending “better error handling.”
When cleanup raises during a processing error, preserve the diagnostic chain in whatever reporting layer you design. Showing only the final message can make a bad record look like an isolated close problem. The lab does not implement a production error aggregator or an ExceptionGroup policy. It exposes the ordinary behavior so a caller can choose an explicit policy and test that policy independently.
Read the test evidence accurately
The 29 author test methods and 20 independent methods passed under Python 3.12.14 and 3.13.5 in normal and optimized modes, for 49 unique test methods. The tests cover empty input, real temporary files, mixed ownership, partial acquisition, failing source iteration, malformed records, cleanup order and cleanup exceptions. Repeating the same suite under another interpreter is a compatibility check. It is not another set of unique behavioral cases, and the test count should not be inflated by multiplying it by every repeated run.
The tests retain references to opened streams. That prevents a misleading result in which an object becomes unreachable and an implementation’s finalization behavior happens to close it before inspection. The test asks whether this code performed the required scoped cleanup, not whether garbage collection might eventually release a forgotten object. A resource test must make the property it measures explicit.
Negative examples are useful when they demonstrate that the checks can detect a real defect. For instance, temporarily replacing the borrowed-stream boundary with an owning context should make the ownership test fail. Perform such mutations only in a disposable copy and restore the original afterward. A passing suite with no challenging failure path can be less informative than a small suite that demonstrably catches the intended regression.
Record the actual interpreter version, command, exit status and output with the publication files. Keep local execution claims narrower than the tested environment. These tests do not show that every operating system, filesystem, text wrapper or future Python version behaves identically. They also say nothing about how often DeepSeek would propose the correct solution without this contract and review process.
Choose the simplest lifetime design
If one file is needed, use one clear file scope. If two known resources have a straightforward nesting relationship, direct nesting can be easier to read than dynamic registration. ExitStack earns its place when the set of resources is optional, variable or assembled programmatically. Adding it everywhere does not automatically improve code, and a reviewer should be able to explain why this particular lifetime needs it.
For an independent list of files, consider processing one file fully before opening the next. That bounds the number of simultaneously open files and makes each ownership scope shorter. It also changes the lab’s acquisition-first timing. If the caller needs all paths to be usable before consuming any borrowed stream, this alternative does not preserve the existing contract without further design.
Do not move a yield of results outside the resource scope casually. A function returning a lazy iterator can postpone reading until after the enclosing with statement has closed its files. Conversely, an iterator that keeps a scope suspended can hold files open longer than callers expect. If you introduce streaming results, specify who closes the iterator and what happens when iteration stops early, then build new tests for that lifetime.
For asynchronous work, use the appropriate asynchronous resource protocol and review cancellation separately. The synchronous example here cannot establish that an awaited cleanup finishes during task cancellation. Our Python asyncio guide discusses cancellation and bounded concurrency. Treat that as a separate design problem rather than translating every with statement mechanically into async with.
Turn an AI review into a checked patch
Ask DeepSeek to report findings in a format you can challenge: the affected statement, the exit path, the observed or predicted outcome, and one minimal test. A claim such as “resource leak possible” is incomplete without identifying the successful acquisition that lacks a matching cleanup obligation. A claim such as “exception lost” needs a concrete exception and the statement that prevents it reaching the caller.
Review one behavior change at a time. If the model proposes a smaller helper, run the same mixed-ownership and failure tests before considering formatting improvements. If it proposes changing exception policy, make that a separate patch with a separate expected result. Combining cleanup, parser rules, logging and retries into one rewrite makes it difficult to determine which assumption caused a regression.
Use the evidence-based code-review workflow to keep findings grounded in a diff and a reproduction. A useful revision can remove duplicated cleanup while preserving every outcome. An attractive revision that closes borrowed inputs or converts errors into zero is behaviorally different, even if its happy-path example prints the same number.
Keep the human decision visible in the review record. The model can identify a tradeoff between acquisition-first behavior and bounded open files, but the application owner decides which contract matters. Once that decision is made, turn it into a named test. Future reviewers can then see why a seemingly simpler rewrite would violate a deliberate requirement rather than assume the complexity is accidental.
Plan the production boundary
The teaching function accepts a finite, manageable collection of trusted inputs. A service accepting user-submitted paths needs a separate authorization and path-selection design. A job reading very large or untrusted records needs explicit size and time limits. A filesystem that can change concurrently introduces consistency questions. None of those requirements is satisfied solely by correct use of a context manager.
Observe outcomes without leaking input data. In a real system, a diagnostic event can identify the processing phase, a safe job identifier, the number of owned resources and the exception category. Avoid logging complete lines, private absolute paths or credentials just to make a cleanup trace readable. Synthetic filenames in the lab are intentionally harmless; production identifiers require their own privacy review.
Output publication introduces another boundary. If a future version writes a result file, releasing the input streams does not make output replacement atomic or durable. Our atomic file-write guide separates staging, replacement and post-publication failures. Keep that work separate from this read-only counting lab so the combined design has explicit guarantees at both boundaries.
Plan failure reporting and ownership at the API edge. The caller should know whether it received a complete result, whether its borrowed objects remain usable, and which operation failed. If a wrapper converts exceptions into a result object, its fields must retain those distinctions. Do not let a generic success flag conceal incomplete processing or a cleanup failure that happened after the arithmetic finished.
Try three review exercises
First, predict the trace for three owned sources where the final open raises. Write the expected sequence before running the test: two successful opens, then the reverse cleanup of those two resources, with no successful third-open event and no returned total. Explain why reading has not begun in this implementation. That explanation distinguishes the actual contract from a per-file processing alternative.
Second, supply an already-positioned borrowed stream. Read one line yourself, call the helper on the remaining lines, and check both the returned total and the final cursor state. The stream should remain open. Ask DeepSeek whether the function “preserves” the input, then challenge any answer that overlooks consumption. This exercise shows how an imprecise verb can hide a meaningful API side effect.
Third, combine malformed input with a failing close. Inspect the exception visible at the top level and follow its context to the earlier processing error. Verify that another owned resource still receives its cleanup call. Do not replace this experiment with a broad exception assertion: the lesson is the relationship between failures and the remaining cleanup obligations.
Use the release checklist
Before accepting a cleanup refactor, answer five questions in plain language. Who owns each resource? When does each cleanup obligation begin? Which exit paths run it? What happens if cleanup itself fails? What evidence verifies those answers? If the explanation relies on “Python takes care of it” without identifying a scope and a protocol, the review is not yet specific enough.
Then check the patch against retained stream references, mixed ownership and injected failures. Compare exception types and chains as well as returned values. Rerun the exact code readers will receive, including any copied or downloaded example. Keep the evidence and limitations beside the implementation so the next change starts from a known contract rather than an assumption.
DeepSeek is most useful here as a reviewer whose suggestions can be tested. The lasting improvement is a small, explicit resource boundary with observable behavior under failure. Once ownership and exit paths are written down, you can evaluate a proposed refactor without relying on its confidence, its length or the polish of its explanation.
Sources & References
Primary references checked October 5, 2026. The Python 3.13 documentation is version-pinned for the language and library behavior discussed here; local execution versions are recorded in the test evidence.
- Python contextlib: contextmanager, nullcontext and ExitStack
- Python language reference: the with statement and finally control flow
- Python data model: resource lifetime and context-manager protocol
- Python tutorial: cleanup actions and exception chaining
- Python I/O documentation: streams and close behavior
- Python tempfile: isolated temporary-directory fixtures
- Python unittest: assertions and exception checks
- DeepSeek official API documentation

[…] the surrounding file and temporary-directory lifecycle, the Python resource-cleanup guide provides a related review workflow. Keep the subprocess fixture’s cleanup rules just as […]
[…] for grouping values, while the owning scope is responsible for the resource lifetime. The related Python resource cleanup guide develops that separation […]