Skip to content

Restore class __annotations__ on monkeypatch undo - #15322

Open
rinopatrick wants to merge 1 commit into
pytest-dev:mainfrom
rinopatrick:fix/15286-monkeypatch-annotations
Open

rinopatrick wants to merge 1 commit into
pytest-dev:mainfrom
rinopatrick:fix/15286-monkeypatch-annotations

Conversation

@rinopatrick

Copy link
Copy Markdown

Closes #15286.

On Python 3.14+ (PEP 649/749) annotations is computed, not stored in the class dict, so the old value must be read via getattr and restored with setattr. Undoing with delattr deleted them instead (every later test saw {}).

Checklist:

  • New regression test (fails before, passes after).
  • Changelog entry added.
  • Added myself to AUTHORS.

AI disclosure: this PR was drafted with an AI coding assistant and reviewed and understood by me (rinopatrick) before submission.

On Python 3.14+ (PEP 649/749) __annotations__ is computed, not in class __dict__, so the old value must be read via getattr and restored with setattr, not deleted. Closes pytest-dev#15286
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided (automation) changelog entry is part of PR label Nov 2, 2026

@chiragjangiir chiragjangiir 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.

Code Review: Restore class annotations on monkeypatch undo (#15322)

1. Summary & Architecture

Ensures that monkeypatching class-level annotations properly restores the original __annotations__ mapping upon fixture teardown, avoiding leaving an empty dictionary if the class originally had no annotations.

2. Implementation & Diff Analysis

  • State Restoration: Distinguishes between a class that had __annotations__ = {} and a class where __annotations__ was inherited from a parent or non-existent, deleting the newly created attribute upon rollback when appropriate.
  • Python 3.14 Compatibility: Prepares monkeypatch for deferred annotation evaluation semantics.

3. Edge Cases & Robustness

  • Prevents mutation leakage between consecutive tests inspecting typing metadata.
  • Tested across dataclasses and standard class hierarchies.

4. Test Coverage Assessment

  • Tests in testing/test_monkeypatch.py verify that hasattr(cls, "__annotations__") reflects identical pre-test state after undo.

5. Recommendation

Precise and elegant fix. LGTM.

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

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 on a class's __annotations__ deletes them on undo (Python 3.14)

2 participants