You can feign immutablility on class attributes by playing with __setattr__
. I don't remember the exact way to do it, but its roughly like this:
class YourClass:
def __setattr__(self, name, value):
if not hasattr(self, name):
super().__setattr__(name, value)
else:
# handle as you wish if the
# attr/value already exists.
# pass, raise, whatever
I say "feign immutability" because there are still cases in which an attr value can change, such as:
I have to mention dataclasses
here, especially with frozen=True
.
Seriously, use dataclasses whenever possible, they're great.