diff --git a/HISTORY.md b/HISTORY.md index eebd0fc5..b9d07af2 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -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) diff --git a/src/cattrs/converters.py b/src/cattrs/converters.py index b0da1082..0eb9aff2 100644 --- a/src/cattrs/converters.py +++ b/src/cattrs/converters.py @@ -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) diff --git a/tests/test_converter.py b/tests/test_converter.py index 6e3b4696..7fd3129a 100644 --- a/tests/test_converter.py +++ b/tests/test_converter.py @@ -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 @@ -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): """