CodeBlanks Logo Icon CodeBlanks

slots and tuple

Learn memory savings with __slots__ and tuple.

What is __slots__?

__slots__ prevents instances of a class from creating a __dict__. Instead only the specified fields get space; this saves memory.

Normally each instance carries a __dict__ dict; this allows dynamic attribute addition but costs memory. Defining __slots__ = ['x', 'y'] makes instances carry only these fields; no __dict__. When thousands of instances are created the saving matters. But dynamic attributes cannot be added; this is a trade-off.

Measuring memory savings

You check whether an instance has __dict__ with hasattr(obj, '__dict__'). In a class with __slots__ this returns False.

In a normal class it returns True. This is the simplest way to confirm slots is working. To measure the saving you use sys.getsizeof; but __dict__ itself is a separate object and getsizeof does not count it. To see the full saving you must add the __dict__ size too.

Practice Compare __dict__ with slots

Write a WithSlots class with __slots__ = ['x', 'y']. Write a WithoutSlots class (no slots). Create an instance of each; set x=1, y=2 on both. Print hasattr(a, '__dict__') and hasattr(b, '__dict__') on separate lines.

Starter code

main.py
# write two classes: one with slots
# create instances and check __dict__

Sample solution

main.py
class WithSlots:
    __slots__ = ["x", "y"]

class WithoutSlots:
    pass

a = WithSlots()
a.x = 1
a.y = 2
b = WithoutSlots()
b.x = 1
b.y = 2
print(hasattr(a, "__dict__"))
print(hasattr(b, "__dict__"))

Expected output

False
True

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match slots concepts

Term Meaning
__slots__ Field list
__dict__ Dynamic dict
memory Saves memory
trade-off Less flexibility

2 What does __slots__ prevent?

main.py
class Point:
    __slots__ = ['x', 'y']
  • Creating __dict__ Correct answer
  • Inheritance
  • Method definitions
  • Calling __init__

Explanation: __slots__ prevents instances from carrying __dict__; it saves memory.

3 Complete the __slots__ definition

Question
class Point:
    ____ = ['x', 'y']
Answer
class Point:
    __slots__ = ['x', 'y']

Explanation: __slots__ = ['x', 'y'] specifies the fields.

All lessons in Expert