Skip to content

gh-144361: Fix NameError when type parameter default refers to a forward name#152208

Open
tangyuan0821 wants to merge 2 commits into
python:mainfrom
tangyuan0821:144361
Open

gh-144361: Fix NameError when type parameter default refers to a forward name#152208
tangyuan0821 wants to merge 2 commits into
python:mainfrom
tangyuan0821:144361

Conversation

@tangyuan0821

@tangyuan0821 tangyuan0821 commented Jun 25, 2026

Copy link
Copy Markdown
Contributor

Fix #144361: PEP 696 + PEP 749 — delayed evaluation of type parameter defaults.

Three call sites in Lib/typing.py eagerly evaluate default (Format.VALUE),
which fails when the default references a name defined later in the module.
Catch NameError and fall back to annotationlib.call_evaluate_function
with Format.FORWARDREF.

@tangyuan0821 tangyuan0821 changed the title gh-144361: Fix NameError when type parameter default refers to a forw… gh-144361: Fix NameError when type parameter default refers to a forward name Jun 25, 2026

@JelleZijlstra JelleZijlstra left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks, please add tests covering the new behavior.

Comment thread Lib/typing.py
args = prepare(cls, args)
try:
args = prepare(cls, args)
except NameError:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I don't understand this part, why do we have to add default here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The C implementation of TypeVar.typing_prepare_subst doesn't catch NameError
when the default is a forward ref — it just raises and returns NULL, so it never
gets a chance to add the default to args. I do both in the except block.

For TypeVarTuple/ParamSpec, their C code delegates to the Python prepare
functions which already handle this themselves, so the outer catch is redundant
for those but harmless.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

PEP696 + PEP749: Defer evaluation of defaults when parametrizing

2 participants