From 2d216a07195d24cc9cce246f395ae5283ffbfb05 Mon Sep 17 00:00:00 2001 From: Marius Gedminas Date: Wed, 15 Jan 2025 12:29:44 +0200 Subject: [PATCH] Fix logic error in get_leaking_objects(objects) Fixes #82, hopefully. I see that I don't have any unit tests for this function, nor do I have any idea how to test it without writing a custom C extension module with intentional refcount bugs. --- CHANGES.rst | 5 ++++- objgraph.py | 20 ++++++++++++++++---- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/CHANGES.rst b/CHANGES.rst index c9ad13d..c2188c2 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -6,7 +6,10 @@ Changes 3.6.3 (unreleased) ------------------ -- Nothing changed yet. +- Fix :func:`get_leaking_objects` with an ``objects`` argument to not ignore + references from other sources. Closes `issue 82 + `_. + Also fix ``get_leaking_objects([])`` causing an UnboudLocalError. 3.6.2 (2024-10-10) diff --git a/objgraph.py b/objgraph.py index d8d5ae9..2af915a 100755 --- a/objgraph.py +++ b/objgraph.py @@ -474,17 +474,29 @@ def get_leaking_objects(objects=None): These could indicate reference-counting bugs in C code. Or they could be legitimate. + If you pass in a list of ``objects``, this function will return + a subset of them that have no referents, otherwise it will look among + all the objects tracked by the garbage collector. + Note that the GC does not track simple objects like int or str. + Example: + + >>> get_leaking_objects(by_type('MyClass')) + ... + .. versionadded:: 1.7 """ + i = None # prevent UnboundLocalError in finally: when objects is [] + gc.collect() + all_objects = gc.get_objects() if objects is None: - gc.collect() - objects = gc.get_objects() + objects = all_objects try: ids = set(id(i) for i in objects) - for i in objects: - ids.difference_update(id(j) for j in gc.get_referents(i)) + for i in all_objects: + if i is not objects: + ids.difference_update(id(j) for j in gc.get_referents(i)) # this then is our set of objects without referrers return [i for i in objects if id(i) in ids] finally: