From b0f61a559b84dc3c105a739e3ed709646bbb36c0 Mon Sep 17 00:00:00 2001 From: Minh Triet Nguyen <751920nguyenminhtriet@gmail.com> Date: Mon, 23 Nov 2026 12:39:59 -0500 Subject: [PATCH 1/2] [http-client-python] Keep containers from dict access attached after property access Reading a list/dict/set field via property after getting it via dict syntax replaced the container in _data, so mutations through the earlier reference were silently dropped from as_dict() and serialization. When deserialization leaves every element untouched (compared by identity), keep the original container instead of swapping in a copy. Fixes #12360 Co-Authored-By: Claude Opus 5.5 --- ...base-container-detach-2026-10-23-18-0-0.md | 7 +++ .../codegen/templates/model_base.py.jinja2 | 26 +++++++++ .../unit/test_model_base_serialization.py | 56 +++++++++++++++++++ 3 files changed, 89 insertions(+) create mode 100644 .chronus/changes/python-model-base-container-detach-2026-10-23-18-0-0.md diff --git a/.chronus/changes/python-model-base-container-detach-2026-10-23-18-0-0.md b/.chronus/changes/python-model-base-container-detach-2026-10-23-18-0-0.md new file mode 100644 index 00000000000..39d6023bde5 --- /dev/null +++ b/.chronus/changes/python-model-base-container-detach-2026-10-23-18-0-0.md @@ -0,0 +1,7 @@ +--- +changeKind: fix +packages: + - "@typespec/http-client-python" +--- + +Fix mutations being dropped when a list, dict or set field is read with dict syntax (`model["field"]`) and then with property syntax (`model.field`). Property access no longer replaces the container already returned by dict access when deserialization leaves its elements unchanged. diff --git a/packages/http-client-python/generator/pygen/codegen/templates/model_base.py.jinja2 b/packages/http-client-python/generator/pygen/codegen/templates/model_base.py.jinja2 index cce55abd9fb..befed1acad6 100644 --- a/packages/http-client-python/generator/pygen/codegen/templates/model_base.py.jinja2 +++ b/packages/http-client-python/generator/pygen/codegen/templates/model_base.py.jinja2 @@ -1453,6 +1453,27 @@ def _failsafe_deserialize_xml( return None +def _has_same_elements(original: typing.Any, deserialized: typing.Any) -> bool: + """Check whether deserializing a container left every element untouched. + + Elements are compared by identity so no custom ``__eq__`` (e.g. on models) is invoked. + + :param any original: The container stored in the model's data. + :param any deserialized: The container produced by deserializing ``original``. + :return: True if ``deserialized`` holds exactly the same element objects as ``original``. + :rtype: bool + """ + if type(original) is not type(deserialized) or len(original) != len(deserialized): + return False + if isinstance(original, list): + return all(a is b for a, b in zip(original, deserialized)) + if isinstance(original, dict): + return all(k in original and original[k] is v for k, v in deserialized.items()) + if isinstance(original, set): + return all(any(a is b for b in original) for a in deserialized) + return False + + # pylint: disable=too-many-instance-attributes class _RestField: def __init__( @@ -1530,6 +1551,11 @@ class _RestField: # For mutable types, store the deserialized value back in _data # so mutations directly affect _data if isinstance(deserialized, (dict, list, set)): + # If deserialization did not transform anything (e.g. list[str], dict[str, str]), + # keep the original container so references previously returned by __getitem__ + # stay attached to the model. + if deserialized is not item and _has_same_elements(item, deserialized): + deserialized = item obj._data[self._rest_name] = deserialized object.__setattr__(obj, cache_attr, True) # Mark as deserialized return deserialized diff --git a/packages/http-client-python/tests/unit/test_model_base_serialization.py b/packages/http-client-python/tests/unit/test_model_base_serialization.py index 2a1d311bf51..c1833c34616 100644 --- a/packages/http-client-python/tests/unit/test_model_base_serialization.py +++ b/packages/http-client-python/tests/unit/test_model_base_serialization.py @@ -4771,6 +4771,62 @@ class MyModel(Model): assert 50 in m.my_set +def test_list_getitem_reference_survives_attribute_access(): + """A list obtained via dict syntax must stay attached after attribute access.""" + + class MyModel(Model): + extensions: list[str] = rest_field() + + m = MyModel(extensions=[".txt"]) + filters = m["extensions"] + _ = m.extensions + filters.append(".csv") + assert m.as_dict()["extensions"] == [".txt", ".csv"] + assert m.extensions == [".txt", ".csv"] + assert json.loads(json.dumps(m, cls=SdkJSONEncoder)) == {"extensions": [".txt", ".csv"]} + + +def test_dict_getitem_reference_survives_attribute_access(): + """A dict obtained via dict syntax must stay attached after attribute access.""" + + class MyModel(Model): + tags: dict[str, str] = rest_field() + + m = MyModel(tags={"a": "1"}) + tags = m["tags"] + _ = m.tags + tags["b"] = "2" + assert m.as_dict()["tags"] == {"a": "1", "b": "2"} + assert m.tags == {"a": "1", "b": "2"} + assert json.loads(json.dumps(m, cls=SdkJSONEncoder)) == {"tags": {"a": "1", "b": "2"}} + + +def test_set_getitem_reference_survives_attribute_access(): + """A set obtained via dict syntax must stay attached after attribute access.""" + + class MyModel(Model): + my_set: set[int] = rest_field() + + m = MyModel(my_set={1}) + ref = m["my_set"] + _ = m.my_set + ref.add(2) + assert m.my_set == {1, 2} + assert m["my_set"] == {1, 2} + + +def test_list_attribute_reference_mutation_serializes(): + """A list obtained via attribute syntax and then mutated must serialize the mutation.""" + + class MyModel(Model): + extensions: list[str] = rest_field() + + m = MyModel(extensions=[".txt"]) + filters = m.extensions + filters.append(".csv") + assert m.as_dict()["extensions"] == [".txt", ".csv"] + + def test_dictionary_set_datetime(): """Test that dictionary with datetime values properly serializes/deserializes.""" from datetime import datetime, timezone From cd782126c31de1b17d99ab65e23bf240b7df6a82 Mon Sep 17 00:00:00 2001 From: Minh Triet Nguyen <751920nguyenminhtriet@gmail.com> Date: Mon, 23 Nov 2026 23:22:27 -0500 Subject: [PATCH 2/2] Use an id set for the set identity check to avoid quadratic time Co-Authored-By: Claude Opus 5.5 --- .../generator/pygen/codegen/templates/model_base.py.jinja2 | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/http-client-python/generator/pygen/codegen/templates/model_base.py.jinja2 b/packages/http-client-python/generator/pygen/codegen/templates/model_base.py.jinja2 index befed1acad6..3cb484128c5 100644 --- a/packages/http-client-python/generator/pygen/codegen/templates/model_base.py.jinja2 +++ b/packages/http-client-python/generator/pygen/codegen/templates/model_base.py.jinja2 @@ -1470,7 +1470,8 @@ def _has_same_elements(original: typing.Any, deserialized: typing.Any) -> bool: if isinstance(original, dict): return all(k in original and original[k] is v for k, v in deserialized.items()) if isinstance(original, set): - return all(any(a is b for b in original) for a in deserialized) + original_ids = {id(x) for x in original} + return all(id(x) in original_ids for x in deserialized) return False