Marcus Johansson
Marcus Johansson

Reputation: 2667

I don't know how to make __slots__ work

How come this code runs 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 slots worked as a restriction. I'm running Python 2.6.6.

Upvotes: 6

Views: 437

Answers (2)

Duncan
Duncan

Reputation: 95732

__slots__ provides a small optimisation of memory use because it can prevent a __dict__ being allocated to store the instance's attributes. This may be useful if you have a very large number of instances.

The restriction you are talking about is mostly an accidental side effect of the way it is implemented. In particular it only stops creation of a __dict__ if your class inherits from a base class that does not have a __dict__ (such as object) and even then it won't stop __dict__ being allocated in any subclasses unless they also define __slots__. It isn't intended as a security mechanism, so it is best not to try to use it as such.

All old-style classes get __dict__ automatically, so __slots__ has no effect. If you inherit from object you will get the effect you are looking for, but basically don't bother with __slots__ until you know you have millions of instances and memory is an issue.

Upvotes: 9

pkit
pkit

Reputation: 8301

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

Change the class declaration to

class Foo(object):
  # etc...

Upvotes: 8

Related Questions