[Tutor] Using new style classes and __slots__

mailing list ml.cyresse at gmail.com
Sat Sep 24 15:49:20 CEST 2005

Hi Kent,


>  >>> class foo(object):
>  ...   __slots__ = ['x', 'y']
>  ...
>  >>> f=foo()
>  >>> f.x=1
>  >>> f.y=2
>  >>> f.z=3
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> AttributeError: 'foo' object has no attribute 'z'
> Take a look at
> http://www.python.org/2.2.3/descrintro.html (search for __slots__)

Thanks for that. I was tearing my hair out trying to figure out why
despite the usage of __slots__ my instances still had a __dict__, and
then I saw the subclass of object, and sure enough... I'm guessing
that's how you get new style classes.

Quite like what I'm seeing, __slots__ and that property() thing will
allow me to remove all my __setattr__ and __getattr__ methods, which
tend to make things crawl a wee bit.

I was almost considering writing setters/getters to get around the
magic methods, but I grew to dislike them after having used Java, I
got annoyed at having to write setters/getters for every public
variable. Of course, I was using Notepad to write the Java programmes,
and then Eclipse helped me  realise why Java programmers value IDE's
so much, it's that automatic generation of set/gets...

> Note to the list: Use of __slots__ is generally discouraged, but IIUC this is exactly the >use case it was designed for so I think it is OK.

Throwing an error on adding a new attribute is just what I need as the
data I'm reading/writing has a very specific format; instead of using
__setattr__ and checking that the attribute already existed, I can
just let __slots__ do the work.

Out of curiosity, if you're using __slots__ with new style, you no
longer have __dict__. So, where does it stick data?

I was using 'self.__dict__["_created"] = False' to set a flag at the
start of __init__ to stop __setattr__ picking up the attributes being
set from parsed data (and running all my type checks, etc.),  but I
won't need that anymore. I could almost hug property(). :)

All in all, this has been an interesting tour around the inner
workings of a class in Python.
Give it another five years, I might be able to read one of those
metaclass explanations and understand it.


Liam Clarke

PS Just for my edification, is there a builtin to determine how much
memory is allocated to an object?

More information about the Tutor mailing list