Skip to content

[http-client-python] Keep containers from dict access attached after property access - #12644

Open
Minh Triet Nguyen (binnguyenx) wants to merge 3 commits into
microsoft:mainfrom
binnguyenx:python/model-base-container-detach
Open

Minh Triet Nguyen (binnguyenx) wants to merge 3 commits into
microsoft:mainfrom
binnguyenx:python/model-base-container-detach

Conversation

@binnguyenx

Copy link
Copy Markdown

Fixes #12360.

Problem

In the generated model runtime (_utils/model_base.py), _RestField.__get__ deserializes list, dict and set fields and stores the result back into obj._data. For primitive containers like list[str] or dict[str, str], the deserializer returns a new container with the same elements. So a container a caller already got through dict access is detached from the model, and later mutations through it are silently dropped:

class M(Model):
    tags: list[str] = rest_field()

m = M(tags=["a"])
ref = m["tags"]
_ = m.tags
ref.append("b")
m.as_dict()["tags"]  # ['a'], expected ['a', 'b']

Only the dict access, then property access order was affected. The other access orders already kept mutations.

Fix

In __get__, if every element of the deserialized container is the same object as in the stored container, the stored container is kept instead of the copy. The new _has_same_elements helper compares elements by identity, not with ==. Using == would call Model.__eq__ when a list of models is compared against its raw list of dicts, and that raises.

Containers whose elements do get converted (models, datetimes, bytes, etc.) behave exactly as before. In those cases the dict view and the property view are different objects by design. The caller's original container is never mutated.

Tests

  • Added test_list_getitem_reference_survives_attribute_access and test_dict_getitem_reference_survives_attribute_access (from the repro in [python] Repro: property access detaches container returned by __getitem__ #12359), plus test_set_getitem_reference_survives_attribute_access. They check as_dict() and SdkJSONEncoder output where relevant.
  • Added test_list_attribute_reference_mutation_serializes as a guard for the order that already worked.
  • The three getitem tests fail on main and pass with the fix. All 127 tests in tests/unit/test_model_base_serialization.py pass.
  • black (with eng/scripts/ci/config/pyproject.toml) is clean on the test file. pylint (with eng/scripts/ci/config/pylintrc) reports the same findings on the rendered model_base.py before and after the change.

I ran these against model_base.py rendered straight from the template, because the generated test packages aren't present locally. I couldn't run the full npm run regenerate / npm run ci, so CI will be the first full regeneration with this change.

🤖 Generated with Claude Code

…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 microsoft#12360

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).
1 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

The set identity check makes property access quadratic, causing a large-set slowdown that should be avoided by checking against a set of original element IDs.

1 open issue
What changed in this PR

Fixes #12360 in the Python client emitter’s generated model runtime by preserving container references obtained through dictionary access when later property access leaves elements unchanged.

Changes:

  • Adds identity-based checks to retain unchanged list, dict, and set containers.
  • Adds regression tests for mixed access patterns and mutation serialization.
  • Records the fix in a package changelog entry.
File Description
packages/​http-client-python/​tests/​unit/​test_model_base_serialization.py Adds container-reference regression tests and a property-first mutation guard.
packages/​http-client-python/​generator/​pygen/​codegen/​templates/​model_base.py.jinja2 Preserves existing containers when deserialized elements retain their identities.
.chronus/​changes/​python-model-base-container-detach-2026-10-23-18-0-0.md Documents the Python model mutation fix.

Review effort: Balanced

@binnguyenx

Copy link
Copy Markdown
Author

Yuchao Yan (@msyyc) could you please comment /azp run on this PR as well? One pipeline (likely the Python emitter tests) was filtered out and needs an authorized user to trigger it. Thanks!

Copilot AI balanced review requested due to automatic review settings November 24, 2026 03:40

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

The nested identity scan makes the first property access for unchanged sets quadratic, introducing a performance regression that should be resolved with object-ID set comparisons.

1 open issue

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 24, 2026 04:22

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟢 Approval recommended

No active review issues are reported for the container-reference preservation change.

1 open issue

Review effort: Balanced

@pkg-pr-new

pkg-pr-new Bot commented Nov 24, 2026

Copy link
Copy Markdown

Open in StackBlitz

npm i https://pkg.pr.new/@typespec/http-client-python@12644

commit: cd78212

@github-actions

Copy link
Copy Markdown
Contributor

All changed packages have been documented.

  • ✅ @typespec/http-client-python
Show changes

@typespec/http-client-python - fix ✏️

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.

@github-actions

Copy link
Copy Markdown
Contributor

Python emitter diff

Baseline gh:0c042af2cedd4acc8430615ad6a30dc0c27b5a56 vs this PR.

Diff summary: 213 file(s), +5751 / -0

Rendered diff: inline on the run summary, or the emitter-diff-html artifact.

Informational check (eng/emitter-diff); does not block the PR.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

emitter:client:python Issue for the Python client emitter: @typespec/http-client-python

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: [python] Reading a model property detaches the container previously returned by __getitem__, dropping mutations

3 participants