1

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.