0

I planned to validate if my Python 3.6 code has any cyclic reference.

Given an object, get_referrers https://docs.python.org/3/library/gc.html#gc.get_referrers returns all objects that refer to the object. However, the following returns []

[o for o in gc.get_objects() if not bool(gc.get_referrers(o))]

which means all objects have at least one referrer.

I also found https://mg.pov.lt/objgraph/objgraph.html#objgraph.is_proper_module that uses modules as roots.

[o for o in gc.get_objects() if objgraph.is_proper_module(o)]

although the modules can still refer to each other... Is this the correct way to find roots?

Joe C
  • 2,757
  • 2
  • 26
  • 46

1 Answers1

2

It's pretty easy to have a GC-tracked object with no referrers known to the GC. For example,

>>> gc.get_referrers([1, 2, 3])
[]

No referrers returned. The GC doesn't know about references on a frame object's value stack (except for frames of suspended generators and coroutines), which is where the reference to the [1, 2, 3] list comes from.

Other cases include objects whose only references live in C global or local variables.

user2357112
  • 260,549
  • 28
  • 431
  • 505