Skip to content
Latchkey

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 closed

Common 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

  1. Close resources deterministically (context managers) instead of relying on __del__.
  2. Guard __del__ bodies so they never raise (check state, swallow expected errors).
  3. 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:
        pass

How 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

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →