Sobes.tech
Junior — Middle

What ways in Python can prevent the modification of an object's state after its creation?

sobes.tech AI

Answer from AI

In Python, to prevent modification of an object's state after its creation, several approaches can be used:

  1. Using immutable data types — for example, tuples instead of lists.

  2. Defining read-only properties with the @property decorator without a setter:

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

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

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

p = ImmutablePoint(1, 2)
print(p.x)  # 1
# p.x = 5  # AttributeError
  1. Using __slots__ to restrict dynamic attribute addition.

  2. Creating immutable classes with namedtuple or dataclasses with frozen=True parameter:

from dataclasses import dataclass

@dataclass(frozen=True)
class Point:
    x: int
    y: int

p = Point(1, 2)
# p.x = 3  # Error, object is frozen
  1. Overriding methods that change state (e.g., __setattr__) to prohibit modifications after initialization.

These methods help create objects with immutable state, which is useful for data safety and multithreaded applications.