Skip to main content

Find out what's still holding a reference to an object that should be dead.

Project description

Find out what’s still holding a reference to an object that should be dead.

refleak.testing.assert_no_instances(cls) checks that no instances of cls remain alive after garbage collection, and for any that do, reports a rendered referrer chain – what’s still holding on to it, and (recursively) what’s holding on to that – so tracking down a reference/GC leak (e.g. a lingering Qt widget, VTK actor, or GUI object in tests) doesn’t require manually poking at gc.get_referrers by hand.

Extracted from mne.utils.misc._assert_no_instances, developed over several years of tracking down reference leaks in MNE-Python, PyVista, and pyvistaqt.

Installation can be performed via pip:

pip install refleak

Usage

import gc
from refleak import testing


class Leaky:
    pass


_leaked = Leaky()  # e.g. accidentally kept alive by a module-level cache
del _leaked
gc.collect()
testing.assert_no_instances(Leaky, when="after test")

A common pattern is a pytest fixture that runs the check on teardown:

import pytest
from refleak.testing import assert_no_instances


@pytest.fixture
def check_no_leaked_widgets(request):
    yield
    assert_no_instances(MyWidget, when="test teardown", request=request)

When references are held, an AssertionError will be thrown. For example:

import gc
from refleak import testing

class Leaky:
    pass

class ClingyParent:
    some_dict: dict

leaked = Leaky()
parent = ClingyParent()
parent.some_dict = {"leak_1": leaked}  # e.g. accidentally kept alive by some object
root_list = ["some_str", leaked, "some_other_str"]
del leaked
gc.collect()
testing.assert_no_instances(Leaky, when="after test")

Would result in:

AssertionError:
Found 1 __main__.Leaky @ after test:
Leaky @ 0x102fe3e00:
├── dict['leak_1']: dict = <len=1>
│   └── __main__.ClingyParent.__dict__['some_dict']: dict = <len=1>
│       └── __main__.__dict__['parent']: dict = <len=15>
└── __main__.root_list[1]: list = <len=3>

Snapshots: only flag new instances

assert_no_instances requires that zero instances exist, which is too strict when some legitimately pre-date the code under test – for example VTK objects held by a plotting theme or a module-level cache. Snapshot records the matching objects that already exist so that only ones created afterwards (and still alive) are reported:

import pytest
from refleak.testing import Snapshot


@pytest.fixture(autouse=True)
def check_vtk_gc(request):
    """Ensure no VTK objects created during a test outlive it."""

    def is_vtk(obj):
        return obj.__class__.__name__.startswith("vtk")

    snap = Snapshot(is_vtk, label="VTK")
    yield
    snap.assert_no_new(when="test teardown", request=request)

match can be a type, a tuple of types, or a predicate callable, and failures render the same referrer chains as assert_no_instances.

Comparison to similar packages

There’s no shortage of tools for poking at Python’s garbage collector; here’s how refleak fits in relative to the ones people reach for most. “Monthly downloads” is from PyPI Stats (July 2026) and includes CI/mirror traffic, so treat it as a rough popularity signal rather than a count of individual users. “Releases (5y)” counts releases in the last five years as a rough maintenance signal.

Package

What it does

Monthly downloads

Latest release

Releases (5y)

refleak

Assert no instances of a class remain alive; on failure, render the referrer chain keeping each survivor alive

new

objgraph

General-purpose object-graph exploration: count objects by type, diff growth between snapshots, render backref/reference graphs via Graphviz

~1.1M

3.6.2 (Oct 2024)

3

Pympler

Broader memory-profiling suite: object sizing (asizeof), live monitoring (muppy), and class-level lifetime tracking (ClassTracker)

~5.5M

1.1 (Jun 2024)

3

guppy3 (heapy)

Python 3 port of the classic guppy/heapy heap analysis toolset, with a query language for slicing the whole heap by type, size, or referrer

~1.2M

3.1.7 (May 2026)

7

pytest-leaks

pytest plugin that reruns each test several times and watches sys.gettotalrefcount() for growth, rather than checking specific classes

~2.4k

0.3.1 (Nov 2019)

0 (unmaintained)

None of the alternatives above do exactly what refleak does: assert that no instances of a specific class remain alive and, on failure, explain why via a rendered referrer chain, in a form meant to be dropped straight into a test suite’s teardown. objgraph and guppy3/heapy can answer the same “why is this still alive” question (and go well beyond it, e.g. full heap graphs and queries), but require driving their APIs interactively or wiring up Graphviz output yourself rather than getting an assertion with a readable message for free. Pympler is aimed more at memory sizing and monitoring over time than one-shot leak assertions. pytest-leaks checks for leaks generically (via total refcount growth across repeated runs) instead of targeting specific classes, so it can flag that something leaked without telling you what or why. If you need full heap introspection or memory-size profiling, reach for objgraph or Pympler/guppy3 instead; if you just want a pytest-friendly assertion that a GUI widget, VTK actor, or other object didn’t leak, and a readable explanation when it did, that’s what refleak is for.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

refleak-0.2.0.tar.gz (28.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

refleak-0.2.0-py3-none-any.whl (20.7 kB view details)

Uploaded Python 3

File details

Details for the file refleak-0.2.0.tar.gz.

File metadata

  • Download URL: refleak-0.2.0.tar.gz
  • Upload date:
  • Size: 28.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for refleak-0.2.0.tar.gz
Algorithm Hash digest
SHA256 b1b7d09fd7c8a89cf8aba8934e9bfbaa6bc59014667e5e4f918ef589b626c8e6
MD5 d57e7ef3bf89c96a6623281dbb5a1ee8
BLAKE2b-256 ca5e98115f02da262a6f3b873269565d8436c593dcbae41bb8075c9be7481ab0

See more details on using hashes here.

Provenance

The following attestation bundles were made for refleak-0.2.0.tar.gz:

Publisher: release.yml on mne-tools/refleak

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file refleak-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: refleak-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 20.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for refleak-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 8e07a7a7f3c65d10645c536ffa439d4f458c45c39cc89836e47d00768fab112c
MD5 93bb77621580a608bf95203852f64ccc
BLAKE2b-256 91184aad91e650e72b29b3567212ce7748a51fcef474db1c567199f9f25ff291

See more details on using hashes here.

Provenance

The following attestation bundles were made for refleak-0.2.0-py3-none-any.whl:

Publisher: release.yml on mne-tools/refleak

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page