215. Immutable Class Design

πŸ”Ή 1. Basic Immutable Class Using property

Copy

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__

Copy

πŸ” Key Takeaway:

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


πŸ”Ή 3. Using namedtuple for Immutable Objects

Copy

πŸ” Key Takeaway:

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


πŸ”Ή 4. Using dataclasses with frozen=True

Copy

πŸ” Key Takeaway:

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


πŸ”Ή 5. Enforcing Immutability with __setattr__

Copy

πŸ” Key Takeaway:

  • Overrides __setattr__ to block modifications.


πŸ”Ή 6. Preventing Deletion with __delattr__

Copy

πŸ” Key Takeaway:

  • __delattr__ prevents accidental deletions.


πŸ”Ή 7. Immutable Singleton Class

Copy

πŸ” Key Takeaway:

  • Ensures only one immutable instance exists.


πŸ”Ή 8. Immutable Dictionary (MappingProxyType)

Copy

πŸ” Key Takeaway:

  • MappingProxyType creates a read-only dictionary.


πŸ”Ή 9. Immutable Object with Custom Hashing

Copy

πŸ” Key Takeaway:

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


πŸ”Ή 10. Enforcing Attribute Restrictions with __slots__ and property

Copy

πŸ” 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