Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Python slots: attribute layout without deep immutability

Last updated: 30 Sept 20264 min read
tutorial
IntermediateBy AITrove Editorial

__slots__ declares named instance storage and can omit an instance dictionary when its inheritance hierarchy permits that layout.

Download Python source kit

Operation contract

The parcel record admits two attributes. A misspelled third attribute fails immediately rather than silently creating unused state. Updating quantity still works: slots restrict attribute layout, not mutation. That distinction is useful when a large collection of small records should not accept arbitrary extension fields.

Failure and ownership boundary

A subclass without its own slots can regain an instance dictionary. Weak references need suitable support, commonly a __weakref__ slot. Multiple inheritance with incompatible layouts can fail at class creation. Use measured object counts and actual memory profiling before selecting slots solely for size; Python weak references: a cache does not own its values and Python super and method resolution: cooperate across mixins affect the result.

Working program

python
class ParcelRecord:
    __slots__ = ("receipt_id", "quantity")
    def __init__(self, receipt_id, quantity):
        self.receipt_id = receipt_id
        self.quantity = quantity

parcel = ParcelRecord("R-0041", 2)
parcel.quantity = 3
print(parcel.quantity)
print(hasattr(parcel, "__dict__"))
try:
    parcel.quanity = 4
except AttributeError:
    print("unknown attribute rejected")

Output

Output
3
False
unknown attribute rejected

Costs and limits

The fixture makes no portable byte-size claim. Slots can avoid a per-instance dictionary but do not shrink referenced strings or other reachable objects. Lookup and allocation effects depend on the interpreter and hierarchy.

Common Mistakes

  • Slots do not make a record immutable.
  • A subclass can restore a dictionary unless its layout also restricts it.

Connected lessons

Python classes: keep instance state separate from class state, Python super and method resolution: cooperate across mixins, Python weak references: a cache does not own its values.

python
slots
Storage details