Skip to content

Raise errors for missing structure handlers more eagerly #577

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Aug 31, 2024
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
9 changes: 9 additions & 0 deletions HISTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,15 @@ The third number is for emergencies when we need to start branches for older rel

Our backwards-compatibility policy can be found [here](https://github.com/python-attrs/cattrs/blob/main/.github/SECURITY.md).

## 24.2.0 (UNRELEASED)

- **Potentially breaking**: The converters raise {class}`StructureHandlerNotFoundError` more eagerly (on hook creation, instead of on hook use).
This helps surfacing problems with missing hooks sooner.
See [Migrations](https://catt.rs/latest/migrations.html#the-default-structure-hook-fallback-factory) for steps to restore legacy behavior.
([#577](https://github.com/python-attrs/cattrs/pull/577))
- Add a [Migrations](https://catt.rs/latest/migrations.html) page, with instructions on migrating changed behavior for each version.
([#577](https://github.com/python-attrs/cattrs/pull/577))

## 24.1.0 (2024-08-28)

- **Potentially breaking**: Unstructuring hooks for `typing.Any` are consistent now: values are unstructured using their runtime type.
Expand Down
1 change: 1 addition & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ validation
preconf
unions
usage
migrations
indepth
```

Expand Down
21 changes: 21 additions & 0 deletions docs/migrations.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Migrations

_cattrs_ sometimes changes in backwards-incompatible ways.
This page contains guidance for changes and workarounds for restoring legacy behavior.

## 24.2.0

### The default structure hook fallback factory

The default structure hook fallback factory was changed to more eagerly raise errors for missing hooks.

The old behavior can be restored by explicitly passing in the old hook fallback factory when instantiating the converter.


```python
>>> from cattrs.fns import raise_error

>>> c = Converter(structure_fallback_factory=lambda _: raise_error)
# Or
>>> c = BaseConverter(structure_fallback_factory=lambda _: raise_error)
```
14 changes: 12 additions & 2 deletions src/cattrs/converters.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,9 @@ def __init__(
prefer_attrib_converters: bool = False,
detailed_validation: bool = True,
unstructure_fallback_factory: HookFactory[UnstructureHook] = lambda _: identity,
structure_fallback_factory: HookFactory[StructureHook] = lambda _: raise_error,
structure_fallback_factory: HookFactory[StructureHook] = lambda t: raise_error(
None, t
),
) -> None:
"""
:param detailed_validation: Whether to use a slightly slower mode for detailed
Expand All @@ -173,6 +175,9 @@ def __init__(

.. versionadded:: 23.2.0 *unstructure_fallback_factory*
.. versionadded:: 23.2.0 *structure_fallback_factory*
.. versionchanged:: 24.2.0
The default `structure_fallback_factory` now raises errors for missing handlers
more eagerly, surfacing problems earlier.
"""
unstruct_strat = UnstructureStrategy(unstruct_strat)
self._prefer_attrib_converters = prefer_attrib_converters
Expand Down Expand Up @@ -1031,7 +1036,9 @@ def __init__(
prefer_attrib_converters: bool = False,
detailed_validation: bool = True,
unstructure_fallback_factory: HookFactory[UnstructureHook] = lambda _: identity,
structure_fallback_factory: HookFactory[StructureHook] = lambda _: raise_error,
structure_fallback_factory: HookFactory[StructureHook] = lambda t: raise_error(
None, t
),
):
"""
:param detailed_validation: Whether to use a slightly slower mode for detailed
Expand All @@ -1043,6 +1050,9 @@ def __init__(

.. versionadded:: 23.2.0 *unstructure_fallback_factory*
.. versionadded:: 23.2.0 *structure_fallback_factory*
.. versionchanged:: 24.2.0
The default `structure_fallback_factory` now raises errors for missing handlers
more eagerly, surfacing problems earlier.
"""
super().__init__(
dict_factory=dict_factory,
Expand Down
10 changes: 8 additions & 2 deletions src/cattrs/gen/_shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

from .._compat import is_bare_final
from ..dispatch import StructureHook
from ..errors import StructureHandlerNotFoundError
from ..fns import raise_error

if TYPE_CHECKING:
Expand All @@ -27,9 +28,14 @@ def find_structure_handler(
elif (
a.converter is not None and not prefer_attrs_converters and type is not None
):
handler = c.get_structure_hook(type, cache_result=False)
if handler == raise_error:
try:
handler = c.get_structure_hook(type, cache_result=False)
except StructureHandlerNotFoundError:
handler = None
else:
# The legacy way, should still work.
if handler == raise_error:
handler = None
elif type is not None:
if (
is_bare_final(type)
Expand Down
12 changes: 12 additions & 0 deletions tests/test_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -721,6 +721,18 @@ class Outer:
assert structured == Outer(Inner(2), [Inner(2)], Inner(2))


def test_default_structure_fallback(converter_cls: Type[BaseConverter]):
"""The default structure fallback hook factory eagerly errors."""

class Test:
"""Unsupported by default."""

c = converter_cls()

with pytest.raises(StructureHandlerNotFoundError):
c.get_structure_hook(Test)


def test_unstructure_fallbacks(converter_cls: Type[BaseConverter]):
"""Unstructure fallback factories work."""

Expand Down