Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 8.12 — __slots__ and Object Memory
Python · Example 1 of 1

Plain objects versus slotted objects

The program prints comparisons, not byte counts, because sizes differ between builds (this page is a 32-bit WebAssembly build). On your own machine print sys.getsizeof values to see the real numbers.

By default every object carries its own __dict__ for attributes, which costs memory. Declaring __slots__ stores attributes in a fixed layout instead, saving memory for millions of small objects and blocking accidental new attributes, at the price of flexibility.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a slotted class Point with x and y. Show that assigning p.z = 1 raises AttributeError and print Point.__slots__.

02

Write a function has_dict(obj) that returns whether an object has a __dict__, and show it for a plain object and a slotted object.

03

Create a Cell class with __slots__ = ("value", "__weakref__"). Make a weak reference to one, delete the object and print what the reference returns.

Explain it without notes

01

Why does a normal Python object use more memory than a slotted one?

02

What do you gain and lose by adding __slots__?

03

Why can't you trust sys.getsizeof alone to measure memory?

04

What is a weak reference, and what does it have to do with slots?

Plain objects versus slotted objects
Sign in to run this example in your browser.

Expected output

True False
['a', 'b', 'c']
AttributeError: 'Slim' object has no attribute 'd' and no __dict__ for setting new attributes
4
TypeError: vars() argument must have __dict__ attribute
1 2 3 ('a', 'b', 'c')
slots object is smaller: True
pointer size in bits: 32
True
5
None