Skip to content

Commit

Permalink
fix: fix failing tests in older versions of python.
Browse files Browse the repository at this point in the history
In the failing tests, the dict value type is a Union of two dataclasses while the dict value instance is an instance of one of the two dataclasses.
If `is_dataclass` is asserted before `_is_supported_generic`, some tests fail because the value is a dataclass but `_decode_dataclass` is heavily relying on the type being a dataclass (f.ex. it calls `fields(cls)`) and Union isn't. If we unpack the union of dataclasses via _is_supported_generic first everything works fine. Hence my change.
Before my change, the code checked whether the **collection** was a dataclass (`is_dataclass(type_) or is_dataclass(xs)`) so the second assert was always false. I assumed it was just a bug. Our tests did not fail in that original code because the `is_dataclass(Union) or is_dataclass(dict)` predicate failed (the collection is not a dataclass) and then the code went on decoding the `Union` and that worked fine (which means that my incorrect code also passed all tests).
I can also roll back the refactoring to _decode_type and keep the code as it was (with the extra conditional branch for checking against the global configuration) if you think this is too risky.
It's a shame there is no test of the _is_dataclass(value) branch because I actually doubt that it ever worked (cause, as mentioned the class must also be a dataclass for things like `fields(cls)` to work)
  • Loading branch information
PJCampi committed May 9, 2024
1 parent 610b772 commit c209ba7
Showing 1 changed file with 2 additions and 2 deletions.
4 changes: 2 additions & 2 deletions dataclasses_json/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,10 +231,10 @@ def _decode_dataclass(cls, kvs, infer_missing):
def _decode_type(type_, value, infer_missing):
if _has_decoder_in_global_config(type_):
return _get_decoder_in_global_config(type_)(value)
if is_dataclass(type_) or is_dataclass(value):
return _decode_dataclass(type_, value, infer_missing)
if _is_supported_generic(type_):
return _decode_generic(type_, value, infer_missing)
if is_dataclass(type_) or is_dataclass(value):
return _decode_dataclass(type_, value, infer_missing)
return _support_extended_types(type_, value)


Expand Down

0 comments on commit c209ba7

Please sign in to comment.