Skip to content

Commit 4330014

Browse files
authored
[3.7] bpo-40663: Correctly handle annotations with subscripts in ast_unparse.c (GH-20156). (GH-20192)
(cherry picked from commit 2135e10) Co-authored-by: Batuhan Taskaya <[email protected]>
1 parent 3613bf0 commit 4330014

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
@@ -237,6 +237,10 @@ def test_annotations(self):
237237
eq("dict[str, int]")
238238
eq("set[str,]")
239239
eq("tuple[str, ...]")
240+
eq("tuple[(str, *types)]")
241+
eq("tuple[xx:yy, (*types,)]")
242+
eq("tuple[str, int, (str, int)]")
243+
eq("tuple[(*int, str, str, (str, int))]")
240244
eq("tuple[str, int, float, dict[str, int]]")
241245
eq("slice[0]")
242246
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
@@ -743,6 +743,24 @@ append_ast_ext_slice(_PyUnicodeWriter *writer, slice_ty slice)
743743
return 0;
744744
}
745745

746+
static int
747+
append_ast_index_slice(_PyUnicodeWriter *writer, slice_ty slice)
748+
{
749+
int level = PR_TUPLE;
750+
expr_ty value = slice->v.Index.value;
751+
if (value->kind == Tuple_kind) {
752+
for (Py_ssize_t i = 0; i < asdl_seq_LEN(value->v.Tuple.elts); i++) {
753+
expr_ty element = asdl_seq_GET(value->v.Tuple.elts, i);
754+
if (element->kind == Starred_kind) {
755+
++level;
756+
break;
757+
}
758+
}
759+
}
760+
APPEND_EXPR(value, level);
761+
return 0;
762+
}
763+
746764
static int
747765
append_ast_slice(_PyUnicodeWriter *writer, slice_ty slice)
748766
{
@@ -752,8 +770,7 @@ append_ast_slice(_PyUnicodeWriter *writer, slice_ty slice)
752770
case ExtSlice_kind:
753771
return append_ast_ext_slice(writer, slice);
754772
case Index_kind:
755-
APPEND_EXPR(slice->v.Index.value, PR_TUPLE);
756-
return 0;
773+
return append_ast_index_slice(writer, slice);
757774
default:
758775
PyErr_SetString(PyExc_SystemError,
759776
"unexpected slice kind");

0 commit comments

Comments
 (0)