Skip to content

Fix monkeypatch.setattr/delattr binding descriptors when raising=False - #14982

Open
IMGillusion wants to merge 1 commit into
pytest-dev:mainfrom
IMGillusion:fix-10646-raising-false-descriptor
Open

Fix monkeypatch.setattr/delattr binding descriptors when raising=False#14982
IMGillusion wants to merge 1 commit into
pytest-dev:mainfrom
IMGillusion:fix-10646-raising-false-descriptor

Conversation

@IMGillusion

@IMGillusion IMGillusion commented Sep 7, 2026

Copy link
Copy Markdown

Fixes #10646.

When monkeypatch.setattr/monkeypatch.delattr are called with raising=False, the attribute existence check currently uses getattr/hasattr, which binds descriptors on the target. This can cause unwanted side effects (e.g. a descriptor __get__ raising, running setup code, or mutating state) even though the caller explicitly disabled the check.

This change makes the raising=False path probe the attribute with inspect.getattr_static, which reads the attribute from the object/class dicts without invoking __get__. The raising=True path is unchanged: it still binds descriptors on purpose, since it needs to detect descriptors that raise AttributeError on access.

Red/green verified: with the new tests (a RaisingDescriptor whose __get__ always fails), raising=True still binds as before while raising=False no longer does, for both setattr and delattr on classes and instances; undo restores the original descriptor. Full test_monkeypatch.py plus test_main/test_collection/test_assertion pass (377 passed), ruff and mypy clean.

AI Disclosure

This PR was developed with the assistance of an AI agent; the account owner verified the root-cause analysis, the red/green test results, and the full test-suite run before submitting.

@psf-chronographer psf-chronographer Bot added the bot:chronographer:provided (automation) changelog entry is part of PR label Sep 7, 2026
When raising=False, the attribute existence check now reads the
attribute statically (inspect.getattr_static) instead of using
getattr/hasattr, so descriptors are no longer bound during the
check and their __get__ side effects do not fire.

closes pytest-dev#10646
@IMGillusion
IMGillusion force-pushed the fix-10646-raising-false-descriptor branch from f4cca6c to 7c0cd16 Compare September 8, 2026 03:30
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.

MonkeyPatch.setattr/delattr cause descriptor binding even when the hasattr check is disabled with raising=False

1 participant