Weakrefs to classes that derive from str

Ron Garret rNOSPAMon at flownet.com
Wed Mar 30 11:23:53 EST 2005


In article <tu-dnbtOEZLOOtffRVn-hA at powergate.ca>,
 Peter Hansen <peter at engcorp.com> wrote:

> Steven Bethard wrote:
> > Ron Garret wrote:
> >> None of the native types (int, float, list, tuple, etc.) can have weak 
> >> references, but wrapping them in a class is supposed to get around 
> >> that.  And it does -- for all classes except str.
> > 
> > Interesting.  Is the wrapping thing documented somewhere?  I didn't see 
> > it in the documentation for weakref.ref (though I have been known to be 
> > blind occasionally) ;)
> 
> I believe it's here: http://docs.python.org/lib/module-weakref.html
> if you search for the string "Not all" and read the next two
> paragraphs.
> 
> On the other hand, it says (there) only that "several builtin
> types such as list and dict ... can add support through
> subclassing", and does not say anything about int, str, etc...

Empirically:

>>> from weakref import ref
>>> def foo(c):
...   class C(c): pass
...   ref(C())
... 
>>> foo(int)
>>> foo(float)
>>> foo(dict)
>>> foo(list)
>>> foo(str)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 3, in foo
TypeError: cannot create weak reference to 'C' object
>>> foo(tuple) 
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 3, in foo
TypeError: cannot create weak reference to 'C' object
>>> foo(long)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 3, in foo
TypeError: cannot create weak reference to 'C' object
>>>

Ah, it appears that non-immediate immutable types don't support 
weakrefs.  Hm...

rg



More information about the Python-list mailing list