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

Ian Kelly ian.g.kelly at gmail.com
Sun May 3 00:43:01 EDT 2015


On Sat, May 2, 2015 at 2:17 PM, Tim Chase <python.list at tim.thechases.com> wrote:
> 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

In general, this shouldn't be necessary. I believe that reference
cycles are guaranteed to be cleaned up in all major implementations of
Python, except that in CPython prior to version 3.4 reference cycles
containing objects with finalizers would not be collected. So the
better advice would be "don't use finalizers in reference cycles if
you need compatibility with Python 3.3 or earlier."



More information about the Python-list mailing list