Inner workings of this Python feature: Can a Python data structure reference itself?

MRAB python at mrabarnett.plus.com
Sat May 2 19:07:03 EDT 2015


On 2015-05-02 22:06, Cecil Westerhof wrote:
> Op Saturday 2 May 2015 22:17 CEST schreef Tim Chase:
>
>> [dangit, had Control down when I hit <enter> and it sent
>> prematurely]
>>
>> On 2015-05-02 13:02, vasudevram wrote:
>>> http://jugad2.blogspot.in/2015/05/can-python-data-structure-reference.html
>>>
>>> https://docs.python.org/2/reference/datamodel.html
>>>
>>> and saw this excerpt:
>>>
>>> [ CPython implementation detail: CPython currently uses a
>>> reference-counting scheme with (optional) delayed
>>> detection of cyclically linked garbage, which collects
>>> most objects as soon as they become unreachable, but is
>>> not guaranteed to collect garbage containing circular
>>> references. ]
>>>
>>> Not sure whether it is relevant to the topic at hand,
>>> since, on the one hand, it uses the words "cyclically
>>> linked", but on the other, it says "garbage collection".
>>
>> The gotcha happens in a case where you do something like this:
>>
>> lst = []
>> lst.append(lst)  # create a cycle
>> del lst
>>
>> This creates a cycle, then makes it unreachable, but the list is
>> still referenced by itself, so the reference count never drops to
>> zero (where it would get GC'd), and thus that item lingers around in
>> memory.
>
> Maybe look at Java? If my memory is correct, the JVM gc reclaims those
> kind of things also.
>
Python _does_ have a secondary mechanism for cleaning up such reference
cycles using mark-and-sweep:

https://docs.python.org/3/reference/datamodel.html




More information about the Python-list mailing list