215. Immutable Class Design

🔹 1. Basic Immutable Class Using property

class ImmutablePoint:
    def __init__(self, x, y):
        self._x = x  # Private variable
        self._y = y

    @property
    def x(self):
        return self._x

    @property
    def y(self):
        return self._y

p = ImmutablePoint(3, 4)
print(p.x)  # ✅ 3
p.x = 10  # ❌ AttributeError: can't set attribute

🔍 Key Takeaway:

  • Using @property, we prevent modifications after object creation.


🔹 2. Immutable Class with __slots__

🔍 Key Takeaway:

  • __slots__ prevents dynamic attribute creation, making the class memory-efficient and immutable.


🔹 3. Using namedtuple for Immutable Objects

🔍 Key Takeaway:

  • namedtuple is a built-in immutable class with fixed fields.


🔹 4. Using dataclasses with frozen=True

🔍 Key Takeaway:

  • Setting frozen=True in @dataclass makes the class immutable.


🔹 5. Enforcing Immutability with __setattr__

🔍 Key Takeaway:

  • Overrides __setattr__ to block modifications.


🔹 6. Preventing Deletion with __delattr__

🔍 Key Takeaway:

  • __delattr__ prevents accidental deletions.


🔹 7. Immutable Singleton Class

🔍 Key Takeaway:

  • Ensures only one immutable instance exists.


🔹 8. Immutable Dictionary (MappingProxyType)

🔍 Key Takeaway:

  • MappingProxyType creates a read-only dictionary.


🔹 9. Immutable Object with Custom Hashing

🔍 Key Takeaway:

  • Immutable objects are hashable, allowing use in sets and dictionaries.


🔹 10. Enforcing Attribute Restrictions with __slots__ and property

🔍 Key Takeaway:

  • __slots__ and @property enforce immutability efficiently.


🚀 Summary: Immutable Class Design Techniques

Method

Key Benefit

@property Decorators

Prevent direct modification

__slots__

Prevents dynamic attribute creation & saves memory

namedtuple

Built-in immutable tuple-like object

@dataclass(frozen=True)

Simplifies immutable class creation

Overriding __setattr__

Blocks modification of attributes

Overriding __delattr__

Prevents deletion of attributes

Singleton Pattern

Ensures only one immutable instance

MappingProxyType

Creates a read-only dictionary

Custom __hash__ Implementation

Allows immutable objects in sets/dicts

Last updated