Skip to content

Commit a4d219b

Browse files
authored
[3.8] bpo-40663: Correctly handle annotations with subscripts in ast_unparse.c (GH-20156). (GH-20191)
(cherry picked from commit 2135e10) Co-authored-by: Batuhan Taskaya <[email protected]>
1 parent 0cc7bec commit a4d219b

File tree

3 files changed

+25
-2
lines changed

3 files changed

+25
-2
lines changed

Lib/test/test_future.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,10 @@ def test_annotations(self):
265265
eq("dict[str, int]")
266266
eq("set[str,]")
267267
eq("tuple[str, ...]")
268+
eq("tuple[(str, *types)]")
269+
eq("tuple[xx:yy, (*types,)]")
270+
eq("tuple[str, int, (str, int)]")
271+
eq("tuple[(*int, str, str, (str, int))]")
268272
eq("tuple[str, int, float, dict[str, int]]")
269273
eq("slice[0]")
270274
eq("slice[0:1]")
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Correctly generate annotations where parentheses are omitted but required
2+
(e.g: ``Type[(str, int, *other))]``.

Python/ast_unparse.c

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -750,6 +750,24 @@ append_ast_ext_slice(_PyUnicodeWriter *writer, slice_ty slice)
750750
return 0;
751751
}
752752

753+
static int
754+
append_ast_index_slice(_PyUnicodeWriter *writer, slice_ty slice)
755+
{
756+
int level = PR_TUPLE;
757+
expr_ty value = slice->v.Index.value;
758+
if (value->kind == Tuple_kind) {
759+
for (Py_ssize_t i = 0; i < asdl_seq_LEN(value->v.Tuple.elts); i++) {
760+
expr_ty element = asdl_seq_GET(value->v.Tuple.elts, i);
761+
if (element->kind == Starred_kind) {
762+
++level;
763+
break;
764+
}
765+
}
766+
}
767+
APPEND_EXPR(value, level);
768+
return 0;
769+
}
770+
753771
static int
754772
append_ast_slice(_PyUnicodeWriter *writer, slice_ty slice)
755773
{
@@ -759,8 +777,7 @@ append_ast_slice(_PyUnicodeWriter *writer, slice_ty slice)
759777
case ExtSlice_kind:
760778
return append_ast_ext_slice(writer, slice);
761779
case Index_kind:
762-
APPEND_EXPR(slice->v.Index.value, PR_TUPLE);
763-
return 0;
780+
return append_ast_index_slice(writer, slice);
764781
default:
765782
PyErr_SetString(PyExc_SystemError,
766783
"unexpected slice kind");

0 commit comments

Comments
 (0)