Skip to content

Commit 2135e10

Browse files
authored
bpo-40663: Correctly handle annotations with subscripts in ast_unparse.c (GH-20156)
1 parent e6578a2 commit 2135e10

File tree

3 files changed

+17
-1
lines changed

3 files changed

+17
-1
lines changed

Lib/test/test_future.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,9 @@ def test_annotations(self):
275275
eq("dict[str, int]")
276276
eq("set[str,]")
277277
eq("tuple[str, ...]")
278+
eq("tuple[(str, *types)]")
279+
eq("tuple[str, int, (str, int)]")
280+
eq("tuple[(*int, str, str, (str, int))]")
278281
eq("tuple[str, int, float, dict[str, int]]")
279282
eq("slice[0]")
280283
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: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -781,8 +781,19 @@ static int
781781
append_ast_subscript(_PyUnicodeWriter *writer, expr_ty e)
782782
{
783783
APPEND_EXPR(e->v.Subscript.value, PR_ATOM);
784+
int level = PR_TUPLE;
785+
expr_ty slice = e->v.Subscript.slice;
786+
if (slice->kind == Tuple_kind) {
787+
for (Py_ssize_t i = 0; i < asdl_seq_LEN(slice->v.Tuple.elts); i++) {
788+
expr_ty element = asdl_seq_GET(slice->v.Tuple.elts, i);
789+
if (element->kind == Starred_kind) {
790+
++level;
791+
break;
792+
}
793+
}
794+
}
784795
APPEND_STR("[");
785-
APPEND_EXPR(e->v.Subscript.slice, PR_TUPLE);
796+
APPEND_EXPR(e->v.Subscript.slice, level);
786797
APPEND_STR_FINISH("]");
787798
}
788799

0 commit comments

Comments
 (0)