[Tutor] What is __weakref__ ?

Steven D'Aprano steve at pearwood.info
Mon Jan 17 23:22:50 CET 2011


Karim wrote:
> 
> Hello,
> 
> I am wondering what is this special class attribut. I know __dict__, 
> slots. I use slots = [] when I want to use a read only class.

(1) slots = [] doesn't do anything special. You have misspelled __slots__.


(2) Classes don't become read only just because you add __slots__ to 
them. All you prevent is adding extra attributes, and why would you wish 
to do that? What harm does it do to you if the caller wants to add extra 
information to your class instances? All that does is make your class 
less useful. I have often wished I could add extra attributes to 
builtins like strings, ints, lists and so forth, but you can't:

 >>> result = 42
 >>> result.extra_info = 0.1
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'extra_info'

I understand why this is the case -- it's a memory optimization -- but 
it's a bloody nuisance. Don't repeat it if you don't have to.


(3) Even if it worked the way you think it works, it is an abuse of 
__slots__. __slots__ is not a mechanism for "read only classes", it is a 
memory optimization for when you need tens or hundreds of millions of 
instances.


> But is anyone could explain with a little example the use of __weakref__?

Have you read the Fine Manual?

http://docs.python.org/reference/datamodel.html#slots


 >>> class K1(object):
...     __slots__ = []  # Don't support weak-refs.
...
 >>> class K2(object):
...    __slots__ = '__weakref__'  # Do support weak-refs.
...
 >>> import weakref
 >>> k1 = K1()
 >>> k2 = K2()
 >>> weakref.ref(k1)
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: cannot create weak reference to 'K1' object
 >>> weakref.ref(k2)
<weakref at 0xb7c6661c; to 'K2' at 0xb7ee762c>



-- 
Steven


More information about the Tutor mailing list