Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I don't know how to make __slots__ work

Tags:

python

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.

like image 426
Marcus Johansson Avatar asked Feb 01 '11 09:02

Marcus Johansson


2 Answers

__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.

like image 61
Duncan Avatar answered Oct 27 '22 21:10

Duncan


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

Change the class declaration to

class Foo(object):
  # etc...
like image 22
pkit Avatar answered Oct 27 '22 19:10

pkit