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

Tim Chase python.list at tim.thechases.com
Sat May 2 16:17:23 EDT 2015


[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.

If you know that you're creating such cyclical structures, it's best
to manually unlink them before freeing them:

  lst = []
  lst.append(lst) # create the cycle
  lst[:] = []   # break the cycle
  # or lst.remove(lst) # though this takes more care
  del lst

-tkc







More information about the Python-list mailing list