ResourceWarning
ResourceWarning: unclosed file <_io.TextIOWrapper name='data.txt'>
Traceback
Traceback (most recent call last):
File "main.py", line 4, in <module>
# f is never closed!
ResourceWarning: unclosed file <_io.TextIOWrapper name='data.txt'>What causes this error
A resource (file, socket, connection) was garbage collected without being properly closed. The resource was opened but never closed or used without a context manager.
How to fix it
Always use `with` statements for files, sockets, and database connections. Run `python -X dev` to see resource warnings. Call `.close()` explicitly in finally blocks when context managers are not practical.
Code that causes this error
def read_file():
f = open("data.txt")
return f.read()
# f is never closed!Fixed code
def read_file():
with open("data.txt") as f:
return f.read()
# f is automatically closedAbout ResourceWarning
A ResourceWarning is issued when a resource (file, socket, database connection) is not properly closed before being garbage collected. By default, ResourceWarning is ignored unless Python is run in development mode (`python -X dev`). The warning indicates a resource leak — the resource will eventually be cleaned up by the garbage collector, but in the meantime it consumes system resources (file descriptors, network connections, memory).
The standard Python idiom to prevent resource leaks is the `with` statement (context manager), which guarantees cleanup even when exceptions occur. Running tests with `-X dev` enables resource warnings, making it easy to find and fix leaks during development. The `tracemalloc` module can provide allocation tracebacks for resource warnings.
Common scenarios
Using deprecated APIs that will be removed in future versions
Performing numerical operations that produce inf or NaN values
Leaving files, sockets, or connections open without proper cleanup
Calling async functions without awaiting the result