Skip to content

fix(rewrite): skip assertion rewriting in class bodies - #14961

Closed
mturac wants to merge 2 commits into
pytest-dev:mainfrom
mturac:fix/issue-9582
Closed

fix(rewrite): skip assertion rewriting in class bodies#14961
mturac wants to merge 2 commits into
pytest-dev:mainfrom
mturac:fix/issue-9582

Conversation

@mturac

@mturac mturac commented Sep 1, 2026

Copy link
Copy Markdown

Fixes #9582

assertion rewriting crashes with TypeError inside Enum class bodies (and any class whose metaclass rejects duplicate keys in namespace).

root cause: the rewriter injects temp variables like @py_assert0 then sets them to None for cleanup. _EnumDict.__setitem__ raises on that second assignment becuase the name is already defined.

fix: skip rewriting assert that sits directly in ClassDef.body. methods inside the class still get rewritten normally — they're seperate FunctionDef nodes visited on their own.

i hit this bug while working on a project that uses asserts in Enum bodies for validation. took a while to figure out it was the rewriter, not the enum itself.

ran the full testing/test_assertrewrite.py suite: 122 passed, 1 skipped. also added two tests — one for the Enum crash case, one to make sure methods still get assertion introspection.

mehmet turac added 2 commits September 2, 2026 02:53
The assertion rewriter injects temporary variables (@py_assert0, etc.)
into class bodies and then cleans them up by assigning None to the same
name. Class namespaces that reject duplicate keys — most notably Enum's
metaclass — raise TypeError on the second assignment.

Skip rewriting assert statements that are direct children of a ClassDef
body. Methods inside the class are still rewritten because they are
FunctionDef nodes whose own bodies are visited in separate iterations.

Fixes pytest-dev#9582
@psf-chronographer psf-chronographer Bot added the bot:chronographer:provided (automation) changelog entry is part of PR label Sep 1, 2026
@RonnyPfannschmidt

Copy link
Copy Markdown
Member

At first glance this is a unattributed simple prompt result without deeper human work

I won't review as such

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.

Assert statements in Enum subclass definitions case errors when assertion rewriting is enabled

3 participants