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

vasudevram vasudevram at gmail.com
Sat May 2 17:07:44 EDT 2015


On Sunday, May 3, 2015 at 1:47:04 AM UTC+5:30, Tim Chase wrote:
> [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

Thanks for the reply. Will check that out.



More information about the Python-list mailing list