Skip to content
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

Newtypes fix #381

Merged
merged 2 commits into from
Jun 10, 2023
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
2 changes: 2 additions & 0 deletions HISTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
- _cattrs_ is now linted with [Ruff](https://beta.ruff.rs/docs/).
- Fix TypedDicts with periods in their field names.
([#376](https://github.com/python-attrs/cattrs/issues/376) [#377](https://github.com/python-attrs/cattrs/pull/377))
- Optimize and improve unstructuring of `Optional` (unions of one type and `None`).
([#380](https://github.com/python-attrs/cattrs/issues/380) [#381](https://github.com/python-attrs/cattrs/pull/381))
- Fix `format_exception` and `transform_error` type annotations.

## 23.1.2 (2023-06-02)
Expand Down
15 changes: 15 additions & 0 deletions src/cattrs/converters.py
Original file line number Diff line number Diff line change
Expand Up @@ -881,13 +881,17 @@ def __init__(
is_frozenset,
lambda cl: self.gen_unstructure_iterable(cl, unstructure_to=frozenset),
)
self.register_unstructure_hook_factory(
is_optional, self.gen_unstructure_optional
)
self.register_unstructure_hook_factory(
is_typeddict, self.gen_unstructure_typeddict
)
self.register_unstructure_hook_factory(
lambda t: get_newtype_base(t) is not None,
lambda t: self._unstructure_func.dispatch(get_newtype_base(t)),
)

self.register_structure_hook_factory(is_annotated, self.gen_structure_annotated)
self.register_structure_hook_factory(is_mapping, self.gen_structure_mapping)
self.register_structure_hook_factory(is_counter, self.gen_structure_counter)
Expand Down Expand Up @@ -938,6 +942,17 @@ def gen_unstructure_attrs_fromdict(
cl, self, _cattrs_omit_if_default=self.omit_if_default, **attrib_overrides
)

def gen_unstructure_optional(self, cl: Type[T]) -> Callable[[T], Any]:
"""Generate an unstructuring hook for optional types."""
union_params = cl.__args__
other = union_params[0] if union_params[1] is NoneType else union_params[1]
handler = self._unstructure_func.dispatch(other)

def unstructure_optional(val, _handler=handler):
return None if val is None else _handler(val)

return unstructure_optional

def gen_structure_typeddict(self, cl: Any) -> Callable[[Dict], Dict]:
"""Generate a TypedDict structure function.

Expand Down
6 changes: 3 additions & 3 deletions tests/test_newtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@

import pytest

from cattrs import BaseConverter
from cattrs import Converter

PositiveIntNewType = NewType("PositiveIntNewType", int)
BigPositiveIntNewType = NewType("BigPositiveIntNewType", PositiveIntNewType)


def test_newtype_structure_hooks(genconverter: BaseConverter):
def test_newtype_structure_hooks(genconverter: Converter):
"""NewTypes should work with `register_structure_hook`."""

assert genconverter.structure("0", int) == 0
Expand Down Expand Up @@ -39,7 +39,7 @@ def test_newtype_structure_hooks(genconverter: BaseConverter):
assert genconverter.structure("51", BigPositiveIntNewType) == 51


def test_newtype_unstructure_hooks(genconverter: BaseConverter):
def test_newtype_unstructure_hooks(genconverter: Converter):
"""NewTypes should work with `register_unstructure_hook`."""

assert genconverter.unstructure(0, int) == 0
Expand Down
41 changes: 41 additions & 0 deletions tests/test_optionals.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
from typing import NewType, Optional

import pytest
from attrs import define

from cattrs._compat import is_py310_plus


def test_newtype_optionals(genconverter):
"""Newtype optionals should work."""
Foo = NewType("Foo", str)

genconverter.register_unstructure_hook(Foo, lambda v: v.replace("foo", "bar"))

@define
class ModelWithFoo:
total_foo: Foo
maybe_foo: Optional[Foo]

assert genconverter.unstructure(ModelWithFoo(Foo("foo"), Foo("is it a foo?"))) == {
"total_foo": "bar",
"maybe_foo": "is it a bar?",
}


@pytest.mark.skipif(not is_py310_plus, reason="3.10+ union syntax")
def test_newtype_modern_optionals(genconverter):
"""Newtype optionals should work."""
Foo = NewType("Foo", str)

genconverter.register_unstructure_hook(Foo, lambda v: v.replace("foo", "bar"))

@define
class ModelWithFoo:
total_foo: Foo
maybe_foo: Foo | None

assert genconverter.unstructure(ModelWithFoo(Foo("foo"), Foo("is it a foo?"))) == {
"total_foo": "bar",
"maybe_foo": "is it a bar?",
}