Python immutability concepts
- User
Python immutability concepts
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Python immutability concepts
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here’s a deep-dive into immutability in Python—what it means, which types are immutable vs. mutable, why it matters, and how you can leverage or even roll your own immutable objects.
An object is immutable if, once created, its internal state cannot be changed. Any “mutation” actually produces a brand-new object.
By contrast, mutable objects let you change their contents in place.
| Type | Examples |
|---|---|
| Numbers | int, float, complex |
| Sequences | str, tuple, bytes |
| Sets/maps | frozenset |
| Other | range, NoneType, bool |
a = 10
print(id(a)) # e.g. 140056271416448
a += 5
print(id(a)) # different! 140056271416576
Above, a += 5 didn’t modify the old integer—it created a new one and rebound the name.
| Type | Examples |
|---|---|
| Sequences | list, bytearray |
| Mappings | dict |
| Sets | set |
| Others | many user-defined objects |
L = [1, 2, 3]
print(id(L))
L.append(4)
print(id(L)) # same id! mutated in place
dict keys or set members.You can enforce immutability in your own classes. Here are 2 common approaches:
__setattr__ & __delattr__class FrozenPoint:
__slots__ = ('x','y') # no __dict__ → smaller footprint
def __init__(self, x, y):
object.__setattr__(self, 'x', x)
object.__setattr__(self, 'y', y)
def __setattr__(self, name, value):
raise AttributeError("Cannot modify immutable instance")
@dataclass(frozen=True)from dataclasses import dataclass
@dataclass(frozen=True)
class Point:
x: float
y: float
p = Point(1,2)
p.x = 5 # ➞ FrozenInstanceError
setfrozendict (e.g. pip install frozendict)copy.copy) duplicates the container, but elements still share references.copy.deepcopy) recursively clones everything.Use deep copy sparingly—immutable designs often eliminate the need for expensive cloning.
tuple (or wrap it in a class that blocks mutations).Anything specific you’d like to explore further?
• More on thread-safety & immutability?
• Internals (memory, caching, interning)?
• Examples of deep-freezing complex data?