__slots__Expert Examples

Restricts instance attributes to a fixed set for memory savings

__slots__ internals

How __slots__ works at the interpreter level.

python
# __slots__ internals
import sys

# Inspect how Python stores attributes
class Example:
    class_var = "shared"

    def __init__(self):
        self.instance_var = "unique"

obj = Example()

# Class vs instance namespace
print("Class namespace keys:", list(Example.__dict__.keys())[:5])
print("Instance namespace:", obj.__dict__)

# Size comparison
print(f"\nClass dict size: {sys.getsizeof(Example.__dict__)} bytes")
print(f"Instance dict size: {sys.getsizeof(obj.__dict__)} bytes")

# Attribute lookup chain
print(f"\nMRO: {[c.__name__ for c in Example.__mro__]}")

Understanding the internals helps with advanced debugging and framework development.

Want to try these examples interactively?

Open Expert Playground