Skip to content
Open
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
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
Expand Up @@ -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__(
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading