-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimmutable.py
More file actions
29 lines (20 loc) · 774 Bytes
/
immutable.py
File metadata and controls
29 lines (20 loc) · 774 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from collections import defaultdict
class Immutable(object):
"""Immutability class.
Attributes:
changed_values (dict): whether or not a property was set.
"""
def __init__(self):
self.__dict__["changed_values"] = defaultdict(bool)
def __setattr__(self, key, value):
if self.changed_values[key]:
raise ImmutabilityException("Cannot change attribute %s." % key)
self.__dict__[key] = value
self.changed_values[key] = True
def __eq__(self, other):
return hash(self) == hash(other)
def __hash__(self):
return hash(self.__class__.__name__ + "@" + str(self.__dict__))
class ImmutabilityException(Exception):
"""Occurs when trying to change an immutable object."""
pass