How to track mutations in models objects? #2600
Answered
by
PrettyWood
balukrishnans
asked this question in
Question
-
Hi, I need to track the mutations in a model object. class User(BaseModel):
id: int
name: str
user = User(1, "John Doe")
user.name = "John Peter" # Here ∆ = {"name": ("John Doe", "John Peter")}
user.id = 3 # Here ∆ = {"id": (1, 3), "name": ("John Doe", "John Peter")}
user(id = 4, name = "Elton") # Here ∆ = {"id": (3, 4), "name": ("John Peter", "Elton")}
Is there any way to track this in |
Beta Was this translation helpful? Give feedback.
Answered by
PrettyWood
Apr 2, 2021
Replies: 1 comment
-
Hi @balukrishnans from pydantic import BaseModel
class User(BaseModel, underscore_attrs_are_private = True):
id: int
name: str
_modifs: dict[str, tuple[object, object]] = {}
def __setattr__(self, key, value):
old_value = self.__dict__.get(key)
super().__setattr__(key, value)
self._modifs[key] = (old_value, value)
user = User(id=1, name="John Doe")
user.name = "John Peter" # Here ∆ = {"name": ("John Doe", "John Peter")}
assert user._modifs == {'name': ('John Doe', 'John Peter')}
user.id = 3 # Here ∆ = {"id": (1, 3), "name": ("John Doe", "John Peter")}
assert user._modifs == {'name': ('John Doe', 'John Peter'), 'id': (1, 3)} ? |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
balukrishnans
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @balukrishnans
Something like this
?