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
2 changes: 2 additions & 0 deletions HISTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@
([#420](https://github.com/python-attrs/cattrs/pull/420))
- Add support for `datetime.date`s to the PyYAML preconfigured converter.
([#393](https://github.com/python-attrs/cattrs/issues/393))
- Remove some unused lines in the unstructuring code.
([#416](https://github.com/python-attrs/cattrs/pull/416))

## 23.1.2 (2023-06-02)

Expand Down
8 changes: 2 additions & 6 deletions src/cattrs/converters.py
Original file line number Diff line number Diff line change
Expand Up @@ -509,16 +509,12 @@ def structure_attrs_fromdict(self, obj: Mapping[str, Any], cl: Type[T]) -> T:

conv_obj = {} # Start with a fresh dict, to ignore extra keys.
for a in fields(cl):
name = a.name

try:
val = obj[name]
val = obj[a.name]
except KeyError:
continue

if name[0] == "_":
name = name[1:]

# try .alias and .name because this code also supports dataclasses!
conv_obj[getattr(a, "alias", a.name)] = self._structure_attribute(a, val)

return cl(**conv_obj)
Expand Down
19 changes: 18 additions & 1 deletion tests/test_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from hypothesis import HealthCheck, assume, given, settings
from hypothesis.strategies import booleans, just, lists, one_of, sampled_from

from cattrs import Converter, UnstructureStrategy
from cattrs import BaseConverter, Converter, UnstructureStrategy
from cattrs.errors import ClassValidationError, ForbiddenExtraKeysError
from cattrs.gen import make_dict_structure_fn, override

Expand Down Expand Up @@ -381,6 +381,23 @@ class C:
assert inst == converter.structure(unstructured, C)


def test_dict_roundtrip_with_alias():
"""
A class with an aliased attribute can be unstructured and structured.
"""

converter = BaseConverter()

@define
class C:
_a: int

inst = C(a=0)
unstructured = converter.unstructure(inst)
assert unstructured == {"_a": 0}
assert converter.structure(unstructured, C) == inst


@given(simple_typed_classes(defaults=True))
def test_type_overrides(cl_and_vals):
"""
Expand Down