Skip to content

Commit

Permalink
fixes #439 by adding support for data classes
Browse files Browse the repository at this point in the history
  • Loading branch information
seperman committed May 14, 2024
1 parent 5f25cc5 commit 429b348
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
3 changes: 3 additions & 0 deletions deepdiff/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -905,6 +905,9 @@ def stringify_param(self, force=None):
result = stringify_element(param, quote_str=self.quote_str)
elif isinstance(param, tuple): # Currently only for numpy ndarrays
result = ']['.join(map(repr, param))
elif hasattr(param, '__dataclass_fields__'):
attrs_to_values = [f"{key}={value}" for key, value in [(i, getattr(param, i)) for i in param.__dataclass_fields__]]
result = f"{param.__class__.__name__}({','.join(attrs_to_values)})"
else:
candidate = repr(param)
try:
Expand Down
35 changes: 35 additions & 0 deletions tests/test_diff_text.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import re
import uuid
from enum import Enum
from dataclasses import dataclass
from typing import List
from decimal import Decimal
from deepdiff import DeepDiff
Expand All @@ -25,6 +26,11 @@ class MyEnum2(str, Enum):
cake = "cake"


@dataclass(frozen=True)
class MyDataClass:
val: int
val2: int


class TestDeepDiffText:
"""DeepDiff Tests."""
Expand Down Expand Up @@ -2073,3 +2079,32 @@ class Bar(PydanticBaseModel):
diff = DeepDiff(t1, t2)
expected = {'values_changed': {'root.stuff[0].thing': {'new_value': 2, 'old_value': 1}}}
assert expected == diff

def test_dataclass1(self):


t1 = MyDataClass(1, 4)
t2 = MyDataClass(2, 4)

diff = DeepDiff(t1, t2, exclude_regex_paths=["any"])
assert {'values_changed': {'root.val': {'new_value': 2, 'old_value': 1}}} == diff

def test_dataclass2(self):

@dataclass(frozen=True)
class MyDataClass:
val: int
val2: int

t1 = {
MyDataClass(1, 4): 10,
MyDataClass(2, 4): 20,
}

t2 = {
MyDataClass(1, 4): 10,
MyDataClass(2, 4): 10,
}

diff = DeepDiff(t1, t2, exclude_regex_paths=["any"])
assert {'values_changed': {'root[MyDataClass(val=2,val2=4)]': {'new_value': 10, 'old_value': 20}}} == diff

0 comments on commit 429b348

Please sign in to comment.