This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: weakref module example relies on behaviour not guaranteed by id()
Type: Stage:
Components: Documentation Versions: Python 3.2, Python 2.7
process
Status: closed Resolution: wont fix
Dependencies: Superseder:
Assigned To: georg.brandl Nosy List: georg.brandl, jackdied, jamesh
Priority: normal Keywords:

Created on 2009-11-20 06:07 by jamesh, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (3)
msg95530 - (view) Author: James Henstridge (jamesh) Date: 2009-11-20 06:07
The documentation for the weakref module contains an example that uses
WeakValueDictionary to implement a id2obj() lookup function that doesn't
store strong references to those objects.

This example implicitly assumes that the id() of an object will be
unique for the lifetime of the interpreter, when it is only unique for
the lifetime of the object.  The problem can be demonstrated like so:

1. create an object "foo"
2. function 1 remembers the id of this object with "oid1 = remember(foo)"
3. "foo" gets garbage collected
4. an object "bar" is created and happens to get the same memory location
5. function 2 remembers the id of this object with "oid2 = remember(bar)"
6. function 1 looks up its stored object ID with "id2obj(oid1)"

In step 6, the object "bar" is returned rather than an exception being
raised.

As well as the example being broken, the weakref module contains the
functionality a programmer would need to do this kind of thing safely:
use the weakref.ref type directly.

It'd be good to replace the example with a better one.
msg95531 - (view) Author: James Henstridge (jamesh) Date: 2009-11-20 06:09
Forgot to include a link to the documentation I was talking about:

    http://docs.python.org/library/weakref#example

This example also appears in the 2.7a0 and 3.2a0 documentation.
msg99858 - (view) Author: Jack Diederich (jackdied) * (Python committer) Date: 2010-02-22 22:23
This is true but /any/ key in the WeakValueDictionary could be reused and result in similar behavior, not just the id() of the inserted value.  I'm closing at "won't fix"
History
Date User Action Args
2022-04-11 14:56:54adminsetgithub: 51615
2010-02-22 22:23:37jackdiedsetstatus: open -> closed

nosy: + jackdied
messages: + msg99858

resolution: wont fix
2009-11-20 06:09:31jameshsetmessages: + msg95531
2009-11-20 06:07:34jameshcreate