11

In Python weakref document( http://docs.python.org/library/weakref.html ), it says that

Several built-in types such as list and dict do not directly support weak references but can add support through subclassing

I think creating weakref for big dict could be useful in some real cases. I'm wondering what's the reason behind that implementation ?

Ryan Ye
  • 3,159
  • 1
  • 22
  • 26

2 Answers2

7

Most of the built-in types are not directly weak referenceable (e.g. str, int, float, list, dict, None), and there are a few that cannot even be made so by sub-classing (e.g. tuples in CPython).

Some details about the underlying implementation of weakrefs for several built-in types can be found in this March-2005 python-list post by Raymond Hettinger.

ws_e_c421
  • 1,043
  • 10
  • 20
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
  • Thanks. Now I could see the reason why tuple and str couldn't be weak referenced. How about list and dict ? Why we have to subclass those types to create weak reference for them ? – Ryan Ye Oct 11 '11 at 09:45
  • If the hints given in the second paragraph aren't enough to go on, then I'm afraid I don't know enough about python's internals to explain further. Maybe you would be better off asking this kind of question on the [python-dev list](http://mail.python.org/mailman/listinfo/python-dev). I'm sure one of the python devs will be able to give you a definitive answer to your question. – ekhumoro Oct 11 '11 at 13:48
-1

My educated guess is that dicts and lists are used internally to implement weakrefs, so you would have an egg-chicken situation here.

rodrigo
  • 94,151
  • 12
  • 143
  • 190