In Python's dataclasses, to make a field effectively constant (i.e., read-only after object creation), there are a few techniques you can use. Here's how you can achieve this:
✅ 1. Using @property for Read-Only Access
This is the most Pythonic way to make a field "constant."
python
from dataclasses import dataclass
@dataclass
class MyData:
_x: int
@property
def x(self):
return self._x
_x is the actual field.
x is a read-only property.
You can read the value but not modify it.
python
data = MyData(10)
print(data.x) # → 10
data.x = 20 # → AttributeError: can't set attribute
✅ 2. Use frozen=True in the dataclass
This makes the entire instance immutable after creation (similar to a constant object).
python
from dataclasses import dataclass
@dataclass(frozen=True)
class MyData:
x: int
y: int
python
data = MyData(1, 2)
data.x = 10 # → FrozenInstanceError
⚠️ Keep in mind:
All fields become read-only.
Mutability within mutable fields (like lists) is not prevented.
Example:
python
from dataclasses import dataclass
@dataclass(frozen=True)
class Point:
x: float
y: float
p = Point(1.0, 2.0)
p.x = 5.0 # Throws dataclasses.FrozenInstanceError
🧪 3. Custom __setattr__ (Advanced)
If you want some fields constant and others mutable:
python
from dataclasses import dataclass
@dataclass
class Example:
x: int
y: int
_initialized: bool = False
def __post_init__(self):
self._initialized = True
def __setattr__(self, name, value):
if getattr(self, "_initialized", False) and name in ("x",):
raise AttributeError(f"{name} is constant and cannot be modified.")
super().__setattr__(name, value)
Before __post_init__: allow setting.
After init: block updates to selected fields (x in this case).
Summary
Method
Read-only Fields
Mutability of Others
Best For
@property
Per field
Fully customizable
Individual constant fields
frozen=True
All fields
Prevents all changes
Fully immutable objects
Custom __setattr__
Customizable
Partially mutable
Complex, fine-grained control
Let me know if you want examples with default values or mutable types (list, dict, etc.).