Skip to content

fix: monkeypatch.setattr undo on objects with custom __setattr__ (#15099) - #15130

Closed
DawnofGenX wants to merge 3 commits into
pytest-dev:mainfrom
DawnofGenX:fix-monkeypatch-custom-setattr-15099-v2
Closed

DawnofGenX wants to merge 3 commits into
pytest-dev:mainfrom
DawnofGenX:fix-monkeypatch-custom-setattr-15099-v2

Conversation

@DawnofGenX

Copy link
Copy Markdown

Problem

Since #14969 (0c601d5, not released yet), monkeypatch.setattr doesn't restore attributes on objects that store them somewhere other than __dict__ through a custom __setattr__/__getattr__. Undo raises AttributeError, and the patched value leaks into later tests.

Changes

  • Only use the __dict__ lookup when name is actually present in the instance __dict__, or when the type uses object.__setattr__. Otherwise fall back to the value from getattr().
  • Add regression test for custom __setattr__ objects
  • Add changelog fragment

Verification

  • 46 passed, 1 skipped (monkeypatch tests)
  • Full suite has pre-existing env-related failures in test_config/test_collection unrelated to this change

When the target has a custom __setattr__ that doesn't write into the
instance __dict__, the old value was recorded as NOTSET, causing undo()
to call delattr() instead of restoring the original value.

Only use the __dict__ lookup when name is actually present in the
instance __dict__, or when the type uses object.__setattr__. Otherwise
fall back to the value from getattr().

Fixes pytest-dev#15099
@psf-chronographer psf-chronographer Bot added the bot:chronographer:provided (automation) changelog entry is part of PR label Oct 4, 2026
…est-dev#15099)

Bind the patched read to a local so mypy doesn't narrow the attribute to
Literal[False] and mark undo() unreachable.
@DawnofGenX

Copy link
Copy Markdown
Author

Closing as a duplicate of #15118 (opened by @Tejas5405 on Oct 1, three days before this one). I should have caught the earlier comment pointing this out on Oct 4 and stood down then. Leaving #15118 to the maintainers.

@DawnofGenX DawnofGenX closed this Oct 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot:chronographer:provided (automation) changelog entry is part of PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant