What are __slots__ used for?

Delaney, Timothy (Tim) tdelaney at avaya.com
Mon Jul 4 23:40:01 EDT 2005


Ric Da Force wrote:

> I am a C# programmer and new to the language and I am trying to debug
> some code which uses this feature.  Can anyone elaborate on what it
> is and how it is used?

__slots__ is used for memory and performance gains in classes that need
them. A class with __slots__ has a fixed memory layout. Classes without
__slots__ use a dictionary for storing attributes.

It is possible to create a class that uses both __slots__ and __dict__
but it's very uncommon.

Some people use __slots__ to restrict the attributes that can be set on
a class (or instance). This is not the intended use, but it does happen.

Tim Delaney



More information about the Python-list mailing list