8

I have some python code where gc.collect() seems to free a lot of memory. Given Python's reference counting nature, I am inclined to think that my program contains a lot of cyclical references. Since some data structures are rather big, I would like to introduce weak references. Now I need to find the circular references, having found a few of the obvious ones, I wonder if one can detect circular references and the objects that form the ring explicitly. So far I have only seen tutorials on how to call gc.collect et. al.

wirrbel
  • 3,173
  • 3
  • 26
  • 49
  • Do these objects have custom `__del__` methods? – Cyphase Aug 10 '15 at 20:56
  • 3
    You may find the [objgraph](http://mg.pov.lt/objgraph/) package useful. It'll create a visualization of the references between objects. [Here's a blog post about circular references and objgraph.](http://engineering.hearsaysocial.com/2013/06/16/circular-references-in-python/) – Cyphase Aug 10 '15 at 20:59
  • I'll also just mention that ideally, you would remove these circular references in the first place, if possible, rather than try to work around them :). – Cyphase Aug 10 '15 at 21:00
  • see http://stackoverflow.com/questions/508277/is-there-a-good-dependency-analysis-tool-for-python – Don Smythe Sep 11 '15 at 10:07

1 Answers1

0

Unless you are overriding the __del__ methods, you should not worry about circular dependencies, as Python is able to properly cope with them.

sorin
  • 161,544
  • 178
  • 535
  • 806
  • ... until you try to use python's multiprocessing and your objects don't pickle anymore. IMO it's a good idea to think about how to avoid cyclic references when designing an application, because it keeps several doors open to optimize performance at a later point. That's *not* the same as premature optimization. – Michel Müller Nov 24 '16 at 03:08