I do not know how to make __slots__ work

Why does this code work for me?

class Foo(): __slots__ = [] def __init__(self): self.should_not_work = "or does it?" print "This code does not run,",self.should_not_work Foo() 

I thought the slots worked as a limitation. I am running Python 2.6.6.

+6
python
source share
2 answers

The __slots__ mechanism works for new-style classes. You must inherit from object .

Change class declaration to

 class Foo(object): # etc... 
+8
source share

__slots__ provides a small optimization of memory usage, as it may prevent __dict__ from __dict__ allocated for storing instance attributes. This can be useful if you have a lot of instances.

The restriction you are talking about is basically a random side effect of how it is implemented. In particular, this stops the creation of __dict__ if your class inherits a base class that does not have __dict__ (for example, object ), and even then it does not stop __dict__ to be allocated in any subclasses if they also do not define __slots__ . It is not intended as a security mechanism, so it is best not to try to use it as such.

All old-style classes receive __dict__ automatically, so __slots__ not valid. If you inherit from object , you will get the effect you are looking for, but basically don't worry about __slots__ until you find out that you have millions of instances and a memory problem.

+9
source share

All Articles