Skip to content

Commit 201b532

Browse files
committed
gh-144361: Fix NameError when type parameter default refers to a forward name
1 parent 56ae0b8 commit 201b532

2 files changed

Lines changed: 22 additions & 3 deletions

File tree

Lib/typing.py

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1099,7 +1099,12 @@ def _typevartuple_prepare_subst(self, alias, args):
10991099
raise TypeError(f"Too few arguments for {alias};"
11001100
f" actual {alen}, expected at least {plen-1}")
11011101
if left == alen - right and self.has_default():
1102-
replacement = _unpack_args(self.__default__)
1102+
try:
1103+
default = self.__default__
1104+
except NameError:
1105+
default = annotationlib.call_evaluate_function(
1106+
self.evaluate_default, annotationlib.Format.FORWARDREF)
1107+
replacement = _unpack_args(default)
11031108
else:
11041109
replacement = args[left: alen - right]
11051110

@@ -1125,7 +1130,12 @@ def _paramspec_prepare_subst(self, alias, args):
11251130
params = alias.__parameters__
11261131
i = params.index(self)
11271132
if i == len(args) and self.has_default():
1128-
args = (*args, self.__default__)
1133+
try:
1134+
default = self.__default__
1135+
except NameError:
1136+
default = annotationlib.call_evaluate_function(
1137+
self.evaluate_default, annotationlib.Format.FORWARDREF)
1138+
args = (*args, default)
11291139
if i >= len(args):
11301140
raise TypeError(f"Too few arguments for {alias}")
11311141
# Special case where Z[[int, str, bool]] == Z[int, str, bool] in PEP 612.
@@ -1185,7 +1195,12 @@ def _generic_class_getitem(cls, args):
11851195
for param in parameters:
11861196
prepare = getattr(param, '__typing_prepare_subst__', None)
11871197
if prepare is not None:
1188-
args = prepare(cls, args)
1198+
try:
1199+
args = prepare(cls, args)
1200+
except NameError:
1201+
default = annotationlib.call_evaluate_function(
1202+
param.evaluate_default, annotationlib.Format.FORWARDREF)
1203+
args = (*args, default)
11891204
_check_generic_specialization(cls, args)
11901205

11911206
new_args = []
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Fix :exc:`NameError` when a type parameter default (PEP 696/PEP 749)
2+
refers to a name defined later in the module. Now three call sites in
3+
:mod:`typing` fall back to :func:`annotationlib.call_evaluate_function`
4+
with :data:`~annotationlib.Format.FORWARDREF` when eager evaluation fails.

0 commit comments

Comments
 (0)