Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions HISTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ Our backwards-compatibility policy can be found [here](https://github.com/python
- For {class}`cattrs.errors.StructureHandlerNotFoundError` and {class}`cattrs.errors.ForbiddenExtraKeysError`
correctly set {attr}`BaseException.args` in `super()` and hence make them pickable.
([#666](https://github.com/python-attrs/cattrs/pull/666))
- The default disambiguation hook factory is now only enabled for converters with `unstructure_strat=AS_DICT` (the default).
Since the strategy doesn't support tuples, it is skipped for `unstructure_strat=AS_TUPLE` converters.
([#673](https://github.com/python-attrs/cattrs/pull/673))

## 25.1.1 (2025-06-04)

Expand Down
188 changes: 92 additions & 96 deletions pdm.lock

Large diffs are not rendered by default.

12 changes: 6 additions & 6 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ lint = [
"ruff>=0.12.2",
]
test = [
"hypothesis>=6.111.2",
"pytest>=8.3.2",
"pytest-benchmark>=4.0.0",
"immutables>=0.20",
"coverage>=7.6.1",
"pytest-xdist>=3.6.1",
"hypothesis>=6.135.26",
"pytest>=8.4.1",
"pytest-benchmark>=5.1.0",
"immutables>=0.21",
"coverage>=7.9.2",
"pytest-xdist>=3.8.0",
]
docs = [
"sphinx>=5.3.0",
Expand Down
6 changes: 5 additions & 1 deletion src/cattrs/converters.py
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,11 @@ def __init__(
(is_tuple, self._structure_tuple),
(is_namedtuple, namedtuple_structure_factory, "extended"),
(is_mapping, self._structure_dict),
(is_supported_union, self._gen_attrs_union_structure, True),
*(
[(is_supported_union, self._gen_attrs_union_structure, True)]
if unstruct_strat is UnstructureStrategy.AS_DICT
else []
),
(is_optional, self._structure_optional),
(
lambda t: is_union_type(t) and t in self._union_struct_registry,
Expand Down
2 changes: 1 addition & 1 deletion tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def converter_cls(request):
)
settings.register_profile("fast", settings.get_profile("tests"), max_examples=10)

settings.load_profile("fast" if "FAST" in environ else "tests")
settings.load_profile("fast" if environ.get("FAST") == "1" else "tests")

collect_ignore_glob = []
if sys.version_info < (3, 10):
Expand Down
91 changes: 60 additions & 31 deletions tests/test_baseconverter.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from hypothesis.strategies import just, one_of

from cattrs import BaseConverter, UnstructureStrategy
from cattrs.errors import StructureHandlerNotFoundError

from ._compat import is_py310_plus
from .typed import nested_typed_classes, simple_typed_attrs, simple_typed_classes
Expand All @@ -28,7 +29,7 @@ def test_simple_roundtrip(cls_and_vals, strat):


@given(
simple_typed_attrs(defaults=True, newtypes=False, allow_nan=False),
simple_typed_attrs(defaults="always", newtypes=False, allow_nan=False),
unstructure_strats,
)
def test_simple_roundtrip_defaults(attr_and_strat, strat):
Expand Down Expand Up @@ -58,7 +59,7 @@ def test_nested_roundtrip(cls_and_vals):
assert inst == converter.structure(converter.unstructure(inst), cl)


@given(nested_typed_classes(kw_only=False, newtypes=False, allow_nan=False))
@given(nested_typed_classes(kw_only="never", newtypes=False, allow_nan=False))
def test_nested_roundtrip_tuple(cls_and_vals):
"""
Nested classes with metadata can be unstructured and restructured.
Expand All @@ -71,24 +72,24 @@ def test_nested_roundtrip_tuple(cls_and_vals):
assert inst == converter.structure(converter.unstructure(inst), cl)


@settings(suppress_health_check=[HealthCheck.filter_too_much, HealthCheck.too_slow])
@settings(suppress_health_check=[HealthCheck.too_slow])
@given(
simple_typed_classes(defaults=False, newtypes=False, allow_nan=False),
simple_typed_classes(defaults=False, newtypes=False, allow_nan=False),
unstructure_strats,
simple_typed_classes(
defaults="never", newtypes=False, allow_nan=False, min_attrs=2
),
simple_typed_classes(
defaults="never", newtypes=False, allow_nan=False, min_attrs=1
),
)
def test_union_field_roundtrip(cl_and_vals_a, cl_and_vals_b, strat):
def test_union_field_roundtrip_dict(cl_and_vals_a, cl_and_vals_b):
"""
Classes with union fields can be unstructured and structured.
"""
converter = BaseConverter(unstruct_strat=strat)
converter = BaseConverter()
cl_a, vals_a, kwargs_a = cl_and_vals_a
assume(strat is UnstructureStrategy.AS_DICT or not kwargs_a)
cl_b, vals_b, _ = cl_and_vals_b
cl_b, _, _ = cl_and_vals_b
a_field_names = {a.name for a in fields(cl_a)}
b_field_names = {a.name for a in fields(cl_b)}
assume(a_field_names)
assume(b_field_names)

common_names = a_field_names & b_field_names
assume(len(a_field_names) > len(common_names))
Expand All @@ -99,25 +100,55 @@ class C:

inst = C(a=cl_a(*vals_a, **kwargs_a))

if strat is UnstructureStrategy.AS_DICT:
assert inst == converter.structure(converter.unstructure(inst), C)
else:
# Our disambiguation functions only support dictionaries for now.
with pytest.raises(ValueError):
converter.structure(converter.unstructure(inst), C)
unstructured = converter.unstructure(inst)
assert inst == converter.structure(converter.unstructure(unstructured), C)

def handler(obj, _):
return converter.structure(obj, cl_a)

converter.register_structure_hook(Union[cl_a, cl_b], handler)
assert inst == converter.structure(converter.unstructure(inst), C)
@settings(suppress_health_check=[HealthCheck.too_slow])
@given(
simple_typed_classes(
defaults="never", newtypes=False, allow_nan=False, kw_only="never", min_attrs=2
),
simple_typed_classes(
defaults="never", newtypes=False, allow_nan=False, kw_only="never", min_attrs=1
),
)
def test_union_field_roundtrip_tuple(cl_and_vals_a, cl_and_vals_b):
"""
Classes with union fields can be unstructured and structured.
"""
converter = BaseConverter(unstruct_strat=UnstructureStrategy.AS_TUPLE)
cl_a, vals_a, _ = cl_and_vals_a
cl_b, _, _ = cl_and_vals_b

@define
class C:
a: Union[cl_a, cl_b]

inst = C(a=cl_a(*vals_a))

# Our disambiguation functions only support dictionaries for now.
raw = converter.unstructure(inst)
with pytest.raises(StructureHandlerNotFoundError):
converter.structure(raw, C)

def handler(obj, _):
return converter.structure(obj, cl_a)

converter.register_structure_hook(Union[cl_a, cl_b], handler)
unstructured = converter.unstructure(inst)
assert inst == converter.structure(unstructured, C)


@pytest.mark.skipif(not is_py310_plus, reason="3.10+ union syntax")
@settings(suppress_health_check=[HealthCheck.filter_too_much, HealthCheck.too_slow])
@settings(suppress_health_check=[HealthCheck.too_slow])
@given(
simple_typed_classes(defaults=False, newtypes=False, allow_nan=False),
simple_typed_classes(defaults=False, newtypes=False, allow_nan=False),
simple_typed_classes(
defaults="never", newtypes=False, allow_nan=False, min_attrs=1
),
simple_typed_classes(
defaults="never", newtypes=False, allow_nan=False, min_attrs=1
),
unstructure_strats,
)
def test_310_union_field_roundtrip(cl_and_vals_a, cl_and_vals_b, strat):
Expand All @@ -126,12 +157,10 @@ def test_310_union_field_roundtrip(cl_and_vals_a, cl_and_vals_b, strat):
"""
converter = BaseConverter(unstruct_strat=strat)
cl_a, vals_a, kwargs_a = cl_and_vals_a
cl_b, vals_b, _ = cl_and_vals_b
cl_b, _, _ = cl_and_vals_b
assume(strat is UnstructureStrategy.AS_DICT or not kwargs_a)
a_field_names = {a.name for a in fields(cl_a)}
b_field_names = {a.name for a in fields(cl_b)}
assume(a_field_names)
assume(b_field_names)

common_names = a_field_names & b_field_names
assume(len(a_field_names) > len(common_names))
Expand All @@ -146,7 +175,7 @@ class C:
assert inst == converter.structure(converter.unstructure(inst), C)
else:
# Our disambiguation functions only support dictionaries for now.
with pytest.raises(ValueError):
with pytest.raises(StructureHandlerNotFoundError):
converter.structure(converter.unstructure(inst), C)

def handler(obj, _):
Expand All @@ -156,7 +185,7 @@ def handler(obj, _):
assert inst == converter.structure(converter.unstructure(inst), C)


@given(simple_typed_classes(defaults=False, newtypes=False, allow_nan=False))
@given(simple_typed_classes(defaults="never", newtypes=False, allow_nan=False))
def test_optional_field_roundtrip(cl_and_vals):
"""
Classes with optional fields can be unstructured and structured.
Expand All @@ -178,7 +207,7 @@ class C:


@pytest.mark.skipif(not is_py310_plus, reason="3.10+ union syntax")
@given(simple_typed_classes(defaults=False, newtypes=False, allow_nan=False))
@given(simple_typed_classes(defaults="never", newtypes=False, allow_nan=False))
def test_310_optional_field_roundtrip(cl_and_vals):
"""
Classes with optional fields can be unstructured and structured.
Expand Down
Loading