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..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 @@ -1453,6 +1453,28 @@ 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): + original_ids = {id(x) for x in original} + return all(id(x) in original_ids for x in deserialized) + return False + + # pylint: disable=too-many-instance-attributes class _RestField: def __init__( @@ -1530,6 +1552,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