__slot__: what is it good for?

Stephen Hansen me+list/python at ixokai.io
Mon Jun 21 11:08:37 EDT 2010


On 6/21/10 7:27 AM, Alexander Eisenhuth wrote:
> Hello out there,
> 
> - what is the reason, that __slots__ are introduced in python?
> 
> - I want to use slots to define a class where no attributes are added at
> runtime. Is that a good idea to use slots for that?

In short, its best to use __slots__ in situations where you are creating
a large number of objects with a set few number of attributes. It lets
you pre-define those variables and the descriptors to access them,
without having to "waste" a dictionary. Unless you're making many
objects, the "waste" of the instance dictionary is largely irrelevant.

Its an optimization: its not an access-control mechanism, or a mechanism
designed to "declare" the attributes of a class before-hand or prevent
attribute creation at runtime.

You could use it that way: but its bad form :)

If you don't want a class to have attributes added at runtime, the
Pythonic way to achieve that is to... simply add attributes at runtime.

Python doesn't really believe in mandates. It believes in good behavior
of adults, awhile acknowledging sometimes an adult might have a
perfectly good reason to do something sneaky (such as add an attribute
to an instance at runtime: its actually *extremely* rare for someone to
do that, so why try to force it away?) down the road that you might not
think of at the time.

-- 

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog: http://meh.ixokai.io/

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 487 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20100621/30e60377/attachment-0001.sig>


More information about the Python-list mailing list