Skip to content

Instantly share code, notes, and snippets.

@AlwxSin
Created April 12, 2018 15:16
Show Gist options
  • Save AlwxSin/2d7cee6731907a4d10c52dd6204b9c2e to your computer and use it in GitHub Desktop.
Save AlwxSin/2d7cee6731907a4d10c52dd6204b9c2e to your computer and use it in GitHub Desktop.
Mixin for tracking class attributes
class TrackAttrsMixin:
"""
Keep eye on TRACK_ATTRS, so we can know if they changed before doing any actions
TRACK_ATTRS should not be empty
"""
TRACK_ATTRS: Iterable[str] = ()
def __init__(self, *args, **kwargs):
if not self.TRACK_ATTRS:
raise ValueError("TRACK_ATTRS should contain at least one value")
super().__init__(*args, **kwargs)
for field in self.TRACK_ATTRS:
value = getattr(self, field)
setattr(self, f"__original_{field}", value)
def has_changed_attributes(self) -> bool:
for field in self.TRACK_ATTRS:
old_val = getattr(self, f"__original_{field}")
new_val = getattr(self, field)
if old_val != new_val:
return True
return False
def attribute_changed(self, field: str) -> bool:
if field in self.TRACK_ATTRS:
old_val = getattr(self, f"__original_{field}")
new_val = getattr(self, field)
return old_val != new_val
else:
raise KeyError(f"Attribute {field} does not in tracked attributes")
def get_original_attribute(self, field):
if field not in self.TRACK_ATTRS:
raise KeyError(f"Attribute {field} is not in the tracked attributes")
return getattr(self, f"__original_{field}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment