gh-130924: Do not create cells for usages of names in local annotations (#131843)

This commit is contained in:
Jelle Zijlstra 2025-03-29 14:15:48 -07:00 committed by GitHub
parent c6b1a07343
commit 425f60b9eb
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 40 additions and 13 deletions

View file

@ -141,6 +141,7 @@ ste_new(struct symtable *st, identifier name, _Py_block_ty block,
ste->ste_needs_classdict = 0;
ste->ste_has_conditional_annotations = 0;
ste->ste_in_conditional_block = 0;
ste->ste_in_unevaluated_annotation = 0;
ste->ste_annotation_block = NULL;
ste->ste_has_docstring = 0;
@ -2538,17 +2539,19 @@ symtable_visit_expr(struct symtable *st, expr_ty e)
VISIT(st, expr, e->v.Slice.step);
break;
case Name_kind:
if (!symtable_add_def_ctx(st, e->v.Name.id,
e->v.Name.ctx == Load ? USE : DEF_LOCAL,
LOCATION(e), e->v.Name.ctx)) {
return 0;
}
/* Special-case super: it counts as a use of __class__ */
if (e->v.Name.ctx == Load &&
_PyST_IsFunctionLike(st->st_cur) &&
_PyUnicode_EqualToASCIIString(e->v.Name.id, "super")) {
if (!symtable_add_def(st, &_Py_ID(__class__), USE, LOCATION(e)))
if (!st->st_cur->ste_in_unevaluated_annotation) {
if (!symtable_add_def_ctx(st, e->v.Name.id,
e->v.Name.ctx == Load ? USE : DEF_LOCAL,
LOCATION(e), e->v.Name.ctx)) {
return 0;
}
/* Special-case super: it counts as a use of __class__ */
if (e->v.Name.ctx == Load &&
_PyST_IsFunctionLike(st->st_cur) &&
_PyUnicode_EqualToASCIIString(e->v.Name.id, "super")) {
if (!symtable_add_def(st, &_Py_ID(__class__), USE, LOCATION(e)))
return 0;
}
}
break;
/* child nodes of List and Tuple will have expr_context set */
@ -2733,6 +2736,9 @@ symtable_visit_params(struct symtable *st, asdl_arg_seq *args)
static int
symtable_visit_annotation(struct symtable *st, expr_ty annotation, void *key)
{
// Annotations in local scopes are not executed and should not affect the symtable
bool is_unevaluated = st->st_cur->ste_type == FunctionBlock;
if ((st->st_cur->ste_type == ClassBlock || st->st_cur->ste_type == ModuleBlock)
&& st->st_cur->ste_in_conditional_block
&& !st->st_cur->ste_has_conditional_annotations)
@ -2764,11 +2770,17 @@ symtable_visit_annotation(struct symtable *st, expr_ty annotation, void *key)
return 0;
}
}
VISIT(st, expr, annotation);
if (is_unevaluated) {
st->st_cur->ste_in_unevaluated_annotation = 1;
}
int rc = symtable_visit_expr(st, annotation);
if (is_unevaluated) {
st->st_cur->ste_in_unevaluated_annotation = 0;
}
if (!symtable_exit_block(st)) {
return 0;
}
return 1;
return rc;
}
static int