__slots__ vs __dict__

Andrew Bennetts andrew-pythonlist at puzzling.org
Wed May 12 18:33:24 EDT 2004


On Thu, May 13, 2004 at 12:07:54AM +0200, Marcus von Appen wrote:
> Jean Brouwers <JBrouwers at ProphICy.com> writes:
> 
> > Classes using __slots__ seem to be quite a bit smaller and faster
> > to instantiate than regular Python classes using __dict__.
> [snip]
> 
> Yes, but instances usually will not have a Class.__dict__ attribute anymore.
> Thus the following code throws an exception on binding new attributes on a 
> per-instance basis:
> 
> # start
> class Foo (object):
>     __slots__ = "_test"
>         
>     def __init__ (self):
>         self._test = None
> 
> if __name__ == "__main__":
>     f = Foo ()
>     f.testvar = "test"
>     return
> # end 

This code is a syntax error for me -- the final return isn't in a function.

> Rebinding __slots__ in __setattr__ fails with a bus error on my system (it 
> should not be possible anyways, because __slots__ is a tuple):
> 
> # start
> class Foo (object):
>     __slots__ = "_test", "_test2"
>         
>     def __init__ (self):
>         self._test = 1
>         self._test2 = 2
>         
>     def __setattr__ (self, name,  value):
>         # just test a simple rebinding
>         self.__slots__ = self.__slots__ 
>         return
>         
> if __name__ == "__main__":
>     f = Foo ()
>     f.testvar = "test"
>     return
> # end 

Also a syntax error.  I also don't get a bus error, just infinite recursion
(because assigning to self.__slots__ calls __setattr__, but __slots__ isn't
an attribute of the instance).  What version of Python, and what platform?
I'm guessing you're on something like FreeBSD where Python has had trouble
coping gracefully with infinite recursion.

-Andrew.





More information about the Python-list mailing list