SoFunction
Updated on 2024-11-19

How python manages memory in circular references

python to recycle garbage objects by reference counting, in some ring data structure (tree, graph ......), there are circular references between objects, for example, the parent node of the tree references the child node, the child node at the same time references the parent node, at this time, by del drop references to the parent and child nodes, the two objects can't be immediately released

Demand:

How to solve such memory management problems?

How to query the reference count of an object?

       import sys

       (obj)

# The query reference count must be 1 more because object also references the query object.

How to solve memory management problems?

  • Weak referencing, via weakref, when del, no longer referenced, added on the referenced side (referencing obj);
  • The use of references requires the use of function calls of the form
#!/usr/bin/python3
 
import weakref
import sys
 
 
class Data(object):
 def __init__(self, value, owner):
   = value
   
  # Declare weak references where the owner is the Node class itself
   = (owner)
  
 # Accessing referenced objects by means of function calls
 def __str__(self):
  return "%s's data, value is %s" % ((), )
  
 def __del__(self):
  print('in_data.__del__')
 
 
class Node(object):
 def __init__(self, value):
   
  # Pass the class itself, also as a parameter, into the Data class
   = Data(value, self)
  
 # Customized object names for easy identification
 def __str__(self):
  return 'Node'
  
 def __del__(self):
  print('in_node.__del__')
  
 
if __name__ == '__main__':
 node = Node(100)
 print()
  
 # Print the reference count of the node object
 print((node) - 1)
  
 # When the node object is deleted, the Data instance object is released when the reference counts to 0.
 del node
  
 input('del done >>>>>')

This is the whole content of this article.