how to find the diff between two different pydantic objets
- User
how to find the diff between two different pydantic objets
- Assistant
how to find the diff between two different pydantic objets
To find the differences between two Pydantic objects, you can compare their attributes directly. Here are a few methods for doing this using Python and the Pydantic library:
You can create a function that compares each attribute of the objects and returns a dictionary of differences.
from pydantic import BaseModel
class Person(BaseModel):
name: str
age: int
email: str
def find_differences(obj1: BaseModel, obj2: BaseModel) -> dict:
differences = {}
for field in obj1.__fields__.keys():
val1 = getattr(obj1, field)
val2 = getattr(obj2, field)
if val1 != val2:
differences[field] = {'obj1': val1, 'obj2': val2}
return differences
# Sample usage
person1 = Person(name="Alice", age=30, email="alice@example.com")
person2 = Person(name="Alice", age=31, email="alice@example.com")
diff = find_differences(person1, person2)
print(diff)
dict ComparisonYou can leverage the dict() method of Pydantic models to make comparisons easier. You can use it to find differences, more succinctly:
from pydantic import BaseModel
class Person(BaseModel):
name: str
age: int
email: str
def find_differences(obj1: BaseModel, obj2: BaseModel) -> dict:
dict1 = obj1.dict(exclude_unset=True)
dict2 = obj2.dict(exclude_unset=True)
differences = {}
for key in set(dict1.keys()).union(dict2.keys()):
val1 = dict1.get(key)
val2 = dict2.get(key)
if val1 != val2:
differences[key] = {'obj1': val1, 'obj2': val2}
return differences
# Sample usage
person1 = Person(name="Alice", age=30, email="alice@example.com")
person2 = Person(name="Alice", age=31, email="alice@example.com")
diff = find_differences(person1, person2)
print(diff)
If you prefer a more general-purpose approach, you can utilize libraries like deepdiff, which can provide detailed differences between complex nested objects.
pip install deepdiff
from deepdiff import DeepDiff
from pydantic import BaseModel
class Person(BaseModel):
name: str
age: int
email: str
# Sample usage
person1 = Person(name="Alice", age=30, email="alice@example.com")
person2 = Person(name="Alice", age=31, email="alice@example.com")
diff = DeepDiff(person1.dict(), person2.dict(), ignore_order=True)
print(diff)
You can use any of the methods mentioned above based on your needs and the complexity of your Pydantic models. Manual comparison is straightforward and easy to customize, while libraries like deepdiff handle more complex scenarios involving nested structures.
Not yet included in a published release.