Prevent resource leaks when functions fail or return early.
What It Does and Why It Matters
A resource leak occurs when a file, socket or connection stays open longer than required. Leaks may exhaust descriptors and block other applications. Put resource ownership close to the code that uses it, with with or try/finally; do not depend on a caller remembering to close a hidden internal handle.
Closing resources promptly is good practice even when the operating system would eventually reclaim them.
Step-by-Step Example
Start with the complete example below. Read the inputs and predict what the final print statement will show before you run it.
from io import StringIO
stream = StringIO("draft")
try:
print(stream.read())
finally:
stream.close()
print(stream.closed)
How the Code Works
- The imports make these standard-library tools available: io.
- The name stream receives the value of StringIO('draft'). Changing this input lets you explore a different case.
- The structured block controls error handling or resource lifetime, including what happens when an operation fails.
- The print calls display the results. Compare these results with the method’s documented return type and the input used.
Expected output:
draft
True
Each displayed line comes from the corresponding calculation or check. The output helps verify the return values before you adapt the example to your own input.
What to Notice
Pay attention to the accepted input types, the returned value and the boundary behavior. Predict what changes if you replace the example input with an empty, zero, negative or missing value, where that value is meaningful for this operation.
If the task uses a library function, inspect its documented exceptions and return type before reusing it inside a larger function.
Where You Would Use This
Use the technique when it makes a real task easier to understand or safer to maintain. Check input and output behavior with small tests before combining it with larger application code.
Practice Exercise
Write a read_file(path) function using with, then test it with a nonexistent file.
Before running your edited example, write down the result you expect. Then test at least one valid boundary or deliberately invalid value, using appropriate exception handling where necessary.
Reference: official Python documentation for the complete API contract and version notes.
Common Beginner Mistakes
- Only closing a resource on the happy path while skipping cleanup for exceptions and early returns.
- Overlooking the documented condition: put resource ownership close to the code that uses it, with with or try/finally; do not depend on a caller remembering to close a hidden internal handle.
Key Takeaways
- Prevent resource leaks when functions fail or return early.
- A resource leak occurs when a file, socket or connection stays open longer than required.
- Write a read_file(path) function using with, then test it with a nonexistent file.