Skip to content

fix(datatree): reject variable-named attribute assignment (#9928) - #11934

Open
aniruddhaadak80 wants to merge 3 commits into
pydata:mainfrom
aniruddhaadak80:fix/datatree-attribute-assignment
Open

aniruddhaadak80 wants to merge 3 commits into
pydata:mainfrom
aniruddhaadak80:fix/datatree-attribute-assignment

Conversation

@aniruddhaadak80

Copy link
Copy Markdown
Contributor

Description

Closes #9928.

DataTree has a __dict__ (for dynamically defined attributes, see GH9068) in addition to __slots__. Variables and child nodes are normally found through AttrAccessMixin.__getattr__, which walks _attr_sources. Assigning tree.variable = value therefore creates an ordinary instance attribute that shadows that lookup, while the stored dataset is unchanged:

import numpy as np
import xarray as xr

ds = xr.Dataset({"variable1": ("x", np.arange(10.0))}, coords={"x": np.arange(10.0)})
dt = xr.DataTree(ds)
dt.variable1 = dt.variable1.sel(x=slice(0, 5))

dt.variable1.sizes   # Frozen({'x': 5})   <- shadowing attribute
dt["variable1"].sizes  # Frozen({'x': 10})  <- stored data
dt.dataset.sizes       # Frozen({'x': 10})

The value written by attribute assignment is also the one used when the tree is exported, so the two views silently disagree.

The fix adds a DataTree.__setattr__ that checks whether the name resolves to a data variable, coordinate variable, or immediate child node. If it does, an AttributeError is raised pointing to __setitem__ assignment. This matches the longstanding Dataset behaviour ("Use setitem style assignment ... instead of assigning variables") and removes the silent divergence. Normal attributes (dt.name, user attributes, private slots) and dt.dataset = ... are unaffected.

A doc/whats-new.rst entry was added under the unreleased "Bug Fixes" section.

Checklist

  • Closes DataTree attribute-like access bug #9928
  • Tests added
  • User visible changes (including notable bug fixes) are documented in whats-new.rst
  • New functions/methods are listed in api.rst (no new public functions/methods)

Tests

New test in xarray/tests/test_datatree.py::TestAccess asserts that assigning to dt.a (where a is a data variable) raises AttributeError, leaves __dict__ untouched, and leaves dt.a and dt["a"] identical.

Actual results in a worktree-local environment (Python 3.12, NumPy 2.5.3, pandas 3.0.6, Windows). The local sitecustomize.py shim on PYTHONPATH that gives the tagless editable dask checkout a parseable __version__ was reused; nothing from it is in the diff.

$ python -m pytest -o addopts="" xarray/tests/test_datatree.py -k attribute_assignment_does_not_shadow -q
  with fix:                       1 passed
  with xarray/core/datatree.py reverted: 1 failed, 192 deselected

$ python -m pytest -o addopts="" xarray/tests/test_datatree.py -q
with fix:       1 failed, 186 passed, 1 skipped, 5 xfailed
without fix:    2 failed, 184 passed, 1 skipped, 5 xfailed

TestIndexing::test_sel_isel_error_has_node_info fails both with and without the change (pre-existing in this environment). TestTreeFromDict::test_roundtrip_to_dict also failed on the unmodified baseline but passed with the fix; it is flaky and unrelated to attribute assignment. No new failures are introduced.

$ python -m ruff check xarray/core/datatree.py xarray/tests/test_datatree.py
All checks passed!
$ python -m ruff format --check xarray/core/datatree.py xarray/tests/test_datatree.py
2 files already formatted

Limitations

  • Only names that currently resolve to an own data variable, coordinate variable, or immediate child are rejected. Inherited coordinates from an ancestor node and names that resolve only through attrs still use ordinary attribute semantics; extending the check there would be a larger API change.
  • This is an error where the previous behaviour silently shadowed; code relying on that shadowing will now fail loudly, which is the intent.
  • Verified on Python 3.12 / NumPy 2.5.3 / pandas 3.0.6 / Windows only. The full suite and docs build were not run on this host.

AI Disclosure

  • This PR contains AI-generated content.
    • I have tested any AI-generated content in my PR.
    • I take responsibility for any AI-generated content in my PR.
      Tools: OpenCode (AI coding agent)

An AI coding agent traced the shadowing to DataTree's __dict__/__getattr__ interaction, drafted the __setattr__ guard and regression test, and ran the verification above. I reviewed the diff and each claimed result.

Copilot AI balanced review requested due to automatic review settings November 24, 2026 05:57

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.

@github-actions github-actions Bot added the topic-DataTree Related to the implementation of a DataTree class label Nov 24, 2026
@aniruddhaadak80

Copy link
Copy Markdown
Contributor Author

CI follow-up: the Mypy jobs flagged redundant-expr on the isinstance(name, str) guard in DataTree.__setattr__ (name is already annotated str). I removed that guard in 292c161c; the targeted regression test still passes and ruff check is clean. No behavior change.

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

topic-DataTree Related to the implementation of a DataTree class

Projects

None yet

Development

Successfully merging this pull request may close these issues.

DataTree attribute-like access bug

2 participants