RFC: Proposal: Deterministic Object Destruction

Ian Kelly ian.g.kelly at gmail.com
Fri Mar 2 00:32:34 EST 2018


On Wed, Feb 28, 2018 at 9:00 PM, ROGER GRAYDON CHRISTMAN <dvl at psu.edu> wrote:
>
> On Wed, Feb 28, 2018, Rick Johnson wrote: >
> On Wednesday, February 28, 2018 at 5:02:17 PM UTC-6, Chris Angelico wrote:
>>
>>> Here's one example: reference cycles. When do they get detected?
>>> Taking a really simple situation:
>>>
>>> class Foo:
>>>     def __init__(self):
>>>         self.self = self
>>
>>*shudders*
>>
>>Can you provide a real world example in which you need an
>>object which circularly references _itself_? This looks like
>>a highly contrived example used to (1) merely win the
>>argument, and (2) Bump fib() up one position from it's
>>current position as "the worst introductory example of how
>>to write a function in the history of programming tutorials"
>
> If you want something that looks like a real world example,
> consider the very common doubly-linked list:
>     [ 1 ] <---> [ 2 ] <---> [ 3 ] <--.....--> [ N ]
>
> This is chock-full of reference cycles, everywhere you see a <-->
>
> Then you have a wrapper List object that has a head referencing
> the 1 node and a tail referencing the N node.
>
> And you decide you don't need that List any more.
>
> You could:
> 1) Take the time the code to carefully delete every single node
> in this linked list, taking the time to set all of the internal references to
> None, or
> 2) Just discard your List object, and let the GC take care of the rest.

3) Use strong references for the left-to-right links and weak
references for the right-to-left links. Poof, no reference cycle.

Even a cyclical graph without ownership relationships can be expressed
without reference cycles. One approach is to build a spanning tree of
strong references and let all the redundant edges be weak. Just be
careful not to cleave your spanning tree when deleting edges. Another,
perhaps simpler, approach is to just have a collection containing all
the nodes and then let *all* the edges be weak.



More information about the Python-list mailing list