Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
17 changes: 17 additions & 0 deletions tests/test_converter.py
Original file line number Diff line number Diff line change
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 = Converter()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you should be testing this with a BaseConverter to hit the changed code path, the Converter uses different machinery.


@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