__slots__ vs __dict__

Marcus von Appen mva at sysfault.org
Wed May 12 18:07:54 EDT 2004


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 

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 

--- gdb backtrace

(gdb) r foo.py
...
Program received signal SIGBUS, Bus error.
0x08070050 in PyDict_GetItem ()
(gdb) bt
#0  0x08070050 in PyDict_GetItem ()
#1  0x08080ab7 in _PyType_Lookup ()
....


Regards
Marcus

-- 
We don't understand the software, and sometimes we don't understand the 
hardware, but we can *see* the blinking lights!



More information about the Python-list mailing list