__slots__ Optimization — ELI5

Imagine packing for a trip. Normally, Python gives each object a giant empty suitcase — you can throw in whatever you want, whenever you want. Socks, a blender, seven hats — no limits. That suitcase is called __dict__, and it’s flexible but heavy.

__slots__ is like replacing that suitcase with a toiletry bag that has exactly three pockets: one for your toothbrush, one for toothpaste, one for deodorant. You can’t fit a blender in there, but it weighs almost nothing and you find things instantly.

When you tell Python “this object will only ever have name, age, and email,” Python doesn’t need to lug around the big flexible suitcase anymore. It creates a tight little container with exactly those three spots.

The result? Each object uses less memory. A lot less. If you’re creating a million user objects, that difference adds up to hundreds of megabytes.

The trade-off is real, though. With slots, you can’t add surprise attributes later. No sneaking a favorite_color onto an object that wasn’t designed for it. You decided what fits at design time, and that’s that.

Most of the time, you don’t need slots. Python’s regular suitcase is fine for everyday objects. But when you’re creating millions of identical objects — like rows in a dataset or points on a map — slots can be the difference between your program running smoothly and running out of memory.

One thing to remember: __slots__ trades flexibility for efficiency. Fixed pockets instead of an open bag — smaller, faster, but no room for surprises.

pythonperformanceoop

See Also