ResourceWarning
PythonWARNINGNotableWarningHIGH confidence

Unclosed resource

Production Risk

Resource leaks cause fd exhaustion under load; always use context managers.

What this means

Issued when a resource (file, socket, database connection) is garbage collected while still open. Silenced by default; enabled with -Wd or in debug mode.

Why it happens
  1. 1A file opened with open() that was never closed
  2. 2A socket that was not closed before garbage collection
  3. 3A database connection left open
How to reproduce

A file object going out of scope without being closed.

trigger — this will error
trigger — this will error
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

Use context managers (with statement)
# Always use 'with' for files, sockets, connections
with open('/etc/hostname') as f:
    content = f.read()
# f is automatically closed when leaving the with block

Why 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

Enable ResourceWarning in tests to catch leaks
# 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.

Code examples
Triggerpython
import warnings
warnings.simplefilter("always", ResourceWarning)
f = open("/etc/hostname")  # ResourceWarning when f is GC-collected unclosed
Handle in testspython
import warnings
warnings.simplefilter("error", ResourceWarning)
# Any unclosed resource in test will raise
Avoid with context managerspython
with open("/etc/hostname") as f:
    content = f.read()
# f is closed automatically — no ResourceWarning
What not to do

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.

Sources
Official documentation ↗

Python Docs — Built-in Exceptions

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Python errors