The documentation for weakref contains the following example: http://docs.python.org/3.1/library/weakref.html ---------------------------------------------- Several built-in types such as list and dict do not directly support weak references but can add support through subclassing: class Dict(dict): pass obj = Dict(red=1, green=2, blue=3) # this object is weak referenceable ---------------------------------------------- While this works fine for list and dict, it does not work for tuple or int: >>> class Tuple(tuple): ... pass ... >>> obj = Tuple() >>> weakref.ref(obj) Traceback (most recent call last): File "", line 1, in TypeError: cannot create weak reference to 'Tuple' object I've tried it in Python 2.5, 2.6, and 3.1.
I parsed the documentation this way: "Several built-in types such as list and dict do not directly support weak references" (true) "but [all of those that do not directly support weak references] can add support through subclassing" I would expect there to be exactly two groups of items: - types that support weak references directly - types where it can be added through subclassing Is there some technical reason why int, tuple, and others cannot support it through subclassing?
The documentation should be rewritten for clarity then. The reason you can't take weakrefs of those types is because they are implemented as "varsized" objects, so there is no constant place to add a weakref list in the memory layout of the objects.
That's fair. I suggest the following change: current text: "Several built-in types such as list and dict do not directly support weak references but can add support through subclassing:" new text: "Several built-in types such as list and dict do not directly support weak references but can add support through subclassing, as shown below. Other built-in types such as tuple and int do not support weak references even when subclassed."