Skip to content

Commit

Permalink
Fix logic error in get_leaking_objects(objects)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
mgedmin committed Jan 15, 2025
1 parent 32b7870 commit 2d216a0
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 5 deletions.
5 changes: 4 additions & 1 deletion CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
<https://github.com/mgedmin/objgraph/issues/82>`_.
Also fix ``get_leaking_objects([])`` causing an UnboudLocalError.


3.6.2 (2024-10-10)
Expand Down
20 changes: 16 additions & 4 deletions objgraph.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down

0 comments on commit 2d216a0

Please sign in to comment.