Skip to content

How to track mutations in models objects? #2600

Discussion options

You must be logged in to vote

Hi @balukrishnans
Something like this

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)}

?

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by balukrishnans
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants