How to enforce immutability to prevent the modification of values in Python

1 Answer

0 votes
# Immutable User in Python (Enforce Immutability)

"""
Python does NOT have built‑in immutability for custom objects,
but you can enforce it using:

1. __slots__               -> prevents adding new attributes
2. private attributes      -> prevents external modification
3. @property (read‑only)    -> exposes values safely
4. no setters              -> prevents mutation
5. overriding __setattr__  -> blocks changes after initialization

This pattern creates a fully immutable object.
"""

class User:
    __slots__ = ("_id", "_name", "_locked")

    def __init__(self, id, name):
        # Assign internal values
        object.__setattr__(self, "_id", id)
        object.__setattr__(self, "_name", name)

        # Lock the object to prevent further modification
        object.__setattr__(self, "_locked", True)

    # Read‑only properties
    @property
    def id(self):
        return self._id

    @property
    def name(self):
        return self._name

    # Prevent modification after initialization
    def __setattr__(self, key, value):
        if getattr(self, "_locked", False):
            raise AttributeError(f"Cannot modify immutable attribute '{key}'")
        object.__setattr__(self, key, value)


# Main program
u = User(42, "Julia")

print("ID:", u.id)
print("Name:", u.name)

# The following lines would raise errors:
# u.id = 100         # Cannot modify immutable attribute 'id'
# u.name = "Tim"     # Cannot modify immutable attribute 'name'
# u._id = 100        # Cannot modify immutable attribute '_id'


"""
run:

ID: 42
Name: Julia

"""

 



answered 8 hours ago by avibootz
edited 8 hours ago by avibootz
...