[Python-ideas] weakrefs

stoneleaf ethan at stoneleaf.us
Fri May 18 18:08:48 CEST 2012



On May 17, 8:10 am, Ethan Furman wrote:
>  From the manual [8.11]:
>
>> A weak reference to an object is not enough to keep the object alive:
>> when the only remaining references to a referent are weak references,
>> garbage collection is free to destroy the referent and reuse its
>> memory for something else.
>
> This leads to a difference in behaviour between CPython and the other
> implementations:  CPython will (currently) immediately destroy any
> objects that only have weak references to them with the result that
> trying to access said object will require making a new one; other
> implementations (at least PyPy, and presumably the others that don't use
> ref-count gc's) can "reach into the grave" and pull back objects that
> don't have any strong references left.

Antione Pitrou wrote:
> This is only true if the object isn't caught in a reference cycle.

Good point -- so I would also like the proposed change in CPython as
well.


Ethan Furman wrote:
> I would like to have the guarantees for weakrefs strengthened such that
> any weakref'ed object that has no strong references left will return
> None instead of the object, even if the object has not yet been garbage
> collected.
>
> Without this stronger guarantee programs that are relying on weakrefs to
> disappear when strong refs are gone end up relying on the gc method
> instead, with the result that the program behaves differently on
> different implementations.

Antione Pitrou wrote:
> Why would they "rely on weakrefs to disappear when strong refs are
> gone"? What is the use case?

Greg Ewing wrote:
> Why do you want this guarantee? It would complicate
> implementations for which ref counting is not the
> native method of managing memory.

My dbf module provides direct access to dbf files.  A retrieved record
is
a singleton object, and allows temporary changes that are not written
to
disk.  Whether those changes are seen by the next incarnation depends
on
(I had thought) whether or not the record with the unwritten changes
has
gone out of scope.

I see two questions that determine whether this change should be made:

  1) How difficult it would be for the non-ref counting
implementations
     to implement

  2) Whether it's appropriate to have objects be changed, but not
saved,
     and then discarded when the strong references are gone so the
next
     incarnation doesn't see the changes, even if the object hasn't
been
     destroyed yet.

~Ethan~

FYI:  For dbf I am going to disallow temporary changes so this won't
be
an immediate issue for me.



More information about the Python-ideas mailing list