Freeze Class Attributes Using setattr Override

Learn how to freeze class attributes in Python by overriding setattr, preventing accidental changes and ensuring data integrity.
Freezing Class Attributes in Python with __setattr__ Override
In Python, classes are highly dynamic. Attributes can be added, changed, or removed on the fly. However, in some situations, you may want to make your class attributes immutable after initialization. This prevents accidental modifications that could lead to bugs or inconsistent state.
Why Freeze Attributes?
Freezing attributes is helpful in data models, configuration objects, or any case where object state should remain constant after creation. By overriding __setattr__
, we can control how and when attributes are assigned.
Basic Example of __setattr__ Override
The following example shows how to make class attributes immutable after initialization:
class Frozen:
def __init__(self, name, age):
super().__setattr__('_frozen', False)
self.name = name
self.age = age
super().__setattr__('_frozen', True)
def __setattr__(self, key, value):
if getattr(self, '_frozen', False):
raise AttributeError(f\\"Cannot modify 'key'. This class is frozen.\\")
super().__setattr__(key, value)
# Example usage
person = Frozen(\\"John\\", 30)
print(person.name) # John
print(person.age) # 30
# Attempting to change will raise an error
# person.age = 31
This ensures that after initialization, no attributes can be modified or added.
Alternative: Using slots for Lightweight Freezing
If your class does not require dynamic attributes, you can combine __slots__
with __setattr__
to further restrict behavior:
class FrozenSlot:
__slots__ = ('name', 'age', '_frozen')
def __init__(self, name, age):
self.name = name
self.age = age
self._frozen = True
def __setattr__(self, key, value):
if hasattr(self, '_frozen') and self._frozen:
raise AttributeError(f\\"Cannot modify 'key'. This class is frozen.\\")
super().__setattr__(key, value)
Conclusion
Overriding __setattr__
provides fine-grained control over attribute assignment. Freezing attributes is a useful design pattern when you need objects with fixed states.
Subscribe to Our YouTube for More
https://blog.arashtad.com/updates/freeze-class-attributes-using-setattr-override/?feed_id=13288&_unique_id=68984f5a04714
Comments
Post a Comment