Unclosed resource
Production Risk
Resource leaks cause fd exhaustion under load; always use context managers.
Issued when a resource (file, socket, database connection) is garbage collected while still open. Silenced by default; enabled with -Wd or in debug mode.
- 1A file opened with open() that was never closed
- 2A socket that was not closed before garbage collection
- 3A database connection left open
A file object going out of scope without being closed.
import warnings
warnings.simplefilter('always', ResourceWarning)
def read_file():
f = open('/etc/hostname')
return f.read()
# f is never closed!
read_file()expected output
ResourceWarning: unclosed file <_io.TextIOWrapper name='/etc/hostname' mode='r' encoding='UTF-8'>
Fix 1
Use context managers (with statement)
WHEN Opening any resource
# Always use 'with' for files, sockets, connections
with open('/etc/hostname') as f:
content = f.read()
# f is automatically closed when leaving the with blockWhy this works
The with statement calls __exit__ (which closes the resource) even if an exception is raised.
Fix 2
Enable ResourceWarning in tests to catch leaks
WHEN Running unit tests
# pytest: add to pytest.ini
[pytest]
filterwarnings = error::ResourceWarning
# Or in test file:
import warnings
warnings.simplefilter("error", ResourceWarning)Why this works
Treating ResourceWarning as an error in tests catches leaks before production.
import warnings
warnings.simplefilter("always", ResourceWarning)
f = open("/etc/hostname") # ResourceWarning when f is GC-collected unclosedimport warnings
warnings.simplefilter("error", ResourceWarning)
# Any unclosed resource in test will raisewith open("/etc/hostname") as f:
content = f.read()
# f is closed automatically — no ResourceWarning✕ Rely on garbage collection to close resources
GC timing is non-deterministic; resources may stay open far longer than expected, exhausting file descriptors or connections.
Python Docs — Built-in Exceptions
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev