Commit f15a6de
authored
🐛 Fix nested dataclass comparison (#120)
Fix how `IsDataclass` handles nested dataclasses so they can be compared
successfully. Previously something like the following would not work:
```python
from dataclasses import dataclass
from dirty_equals import IsDataclass
@DataClass
class Address:
street: str
zip_code: str
@DataClass
class Person:
name: str
address: Address
person = Person(
name='Alice',
address=Address(street='123 Main St', zip_code='12345'),
)
assert person == IsDataclass(
name='Alice',
address=IsDataclass(street='123 Main St', zip_code='12345')
)
```
This is a result of `IsDataclass` converting dataclasses to a dictionary
for comparison using `dataclasses.asdict`, which _recursively_ converts
dataclasses to plain dictionaries. Thus the inner `IsDataclass` fails,
because the other side of the comparison is now a dictionary, not a
dataclass.
These changes fix this by shallowly converting the dataclass to a
dictionary using [the approach recommended in the dataclasses
documentation](https://docs.python.org/3/library/dataclasses.html#dataclasses.asdict):
```python
{field.name: getattr(obj, field.name) for field in fields(obj)}
```
These changes also include a test for nested dataclass comparisons to
ensure this works as expected and continues to work in the future.1 parent 32f23d1 commit f15a6de
2 files changed
+24
-4
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
2 | 2 | | |
3 | 3 | | |
4 | 4 | | |
5 | | - | |
| 5 | + | |
6 | 6 | | |
7 | 7 | | |
8 | 8 | | |
| |||
486 | 486 | | |
487 | 487 | | |
488 | 488 | | |
489 | | - | |
490 | | - | |
| 489 | + | |
| 490 | + | |
491 | 491 | | |
492 | | - | |
| 492 | + | |
| 493 | + | |
493 | 494 | | |
494 | 495 | | |
495 | 496 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
39 | 39 | | |
40 | 40 | | |
41 | 41 | | |
| 42 | + | |
| 43 | + | |
| 44 | + | |
| 45 | + | |
| 46 | + | |
| 47 | + | |
| 48 | + | |
| 49 | + | |
| 50 | + | |
| 51 | + | |
| 52 | + | |
| 53 | + | |
| 54 | + | |
| 55 | + | |
| 56 | + | |
42 | 57 | | |
43 | 58 | | |
44 | 59 | | |
| |||
373 | 388 | | |
374 | 389 | | |
375 | 390 | | |
| 391 | + | |
| 392 | + | |
| 393 | + | |
| 394 | + | |
376 | 395 | | |
377 | 396 | | |
378 | 397 | | |
| |||
0 commit comments