pythongarbage-collectioncircular-dependencypython-c-api

Why does Python implement cyclic GC on types that reference non-container types


Checking docs: Supporting Cyclic Garbage Collection

Python’s support for detecting and collecting garbage which involves circular references requires support from object types which are “containers” for other objects which may also be containers. Types which do not store references to other objects, or which only store references to atomic types (such as numbers or strings), do not need to provide any explicit support for garbage collection.

However I was looking at the implementation of bytearray, while the bytearray itself doesn't use cyclic GC, the iterator that it creates does. My issue is that according to the docs it doesn't need it because bytearray iterator doesn't reference any object that may be containers only the bytearray itself that created it, hence no chance of cyclic dependency. What's the reason behind that?


Solution

  • It's because of subclasses:

    class BytearrayWithACircularReference(bytearray):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.circular_reference = iter(self)
    
    BytearrayWithACircularReference()
    

    If the bytearray iterator type didn't have GC support, this would be a memory leak.