Python "pytest.PytestUnraisableExceptionWarning" in CI
pytest reports PytestUnraisableExceptionWarning when an exception is raised in a context Python cannot propagate, typically a __del__ finalizer or a weakref callback. Under filterwarnings = error it fails the suite.
What this error means
A run reports "PytestUnraisableExceptionWarning: Exception ignored in: <function ...__del__>" and, with warnings-as-errors, fails the test.
pytest
PytestUnraisableExceptionWarning: Exception ignored in: <function Resource.__del__ at 0x...>
Traceback (most recent call last):
...
OSError: handle already closedCommon causes
An exception raised inside __del__
A finalizer touched an already-closed resource, raising during garbage collection where it cannot propagate.
A weakref callback that errored
A callback fired during collection and raised, surfacing as an unraisable warning.
How to fix it
Make finalizers defensive and close resources explicitly
- Close resources deterministically (context managers) instead of relying on __del__.
- Guard __del__ bodies so they never raise (check state, swallow expected errors).
- Find the source via the traceback in the warning and fix the finalizer.
Python
def __del__(self):
try:
if getattr(self, "_handle", None) is not None:
self._handle.close()
except Exception:
passHow to prevent it
- Prefer context managers over __del__ for cleanup.
- Never let a finalizer raise.
- Run with filterwarnings=error to catch these early.
Related guides
Python "ResourceWarning: unclosed" failing pytest in CIFix "ResourceWarning: unclosed file/socket" that fails pytest in CI - a file or socket was garbage-collected…
Python "pandas FutureWarning treated as error" in CIFix a pandas FutureWarning that fails CI - filterwarnings=error turns a deprecation warning from pandas into…
pytest "DeprecationWarning" Failing CI via filterwarnings=errorFix pytest runs failing because filterwarnings=error (or -W error) turns a DeprecationWarning into a test fai…