]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.7] bpo-40663: Correctly handle annotations with subscripts in ast_unparse.c (GH...
authorBatuhan Taskaya <isidentical@gmail.com>
Fri, 22 May 2020 22:32:34 +0000 (01:32 +0300)
committerGitHub <noreply@github.com>
Fri, 22 May 2020 22:32:34 +0000 (23:32 +0100)
(cherry picked from commit 2135e10dc717c00d10d899d232bebfc59bb25032)

Co-authored-by: Batuhan Taskaya <batuhanosmantaskaya@gmail.com>
Lib/test/test_future.py
Misc/NEWS.d/next/Core and Builtins/2020-05-17-20-38-12.bpo-40663.u2aiZf.rst [new file with mode: 0644]
Python/ast_unparse.c

index 2aed01095aa7eec4d313ee7b95e85c3dc235ade0..13a4f6f3cc6a3977dd6dd3ef000e6b3a9a1c6610 100644 (file)
@@ -237,6 +237,10 @@ class AnnotationsFutureTestCase(unittest.TestCase):
         eq("dict[str, int]")
         eq("set[str,]")
         eq("tuple[str, ...]")
+        eq("tuple[(str, *types)]")
+        eq("tuple[xx:yy, (*types,)]")
+        eq("tuple[str, int, (str, int)]")
+        eq("tuple[(*int, str, str, (str, int))]")
         eq("tuple[str, int, float, dict[str, int]]")
         eq("slice[0]")
         eq("slice[0:1]")
diff --git a/Misc/NEWS.d/next/Core and Builtins/2020-05-17-20-38-12.bpo-40663.u2aiZf.rst b/Misc/NEWS.d/next/Core and Builtins/2020-05-17-20-38-12.bpo-40663.u2aiZf.rst
new file mode 100644 (file)
index 0000000..5041abc
--- /dev/null
@@ -0,0 +1,2 @@
+Correctly generate annotations where parentheses are omitted but required
+(e.g: ``Type[(str, int, *other))]``.
index 93b3ecffb017ed9d179fcdc491a15bc1aec72a9c..7ed4b4f18082307365605a867eb327230afce18b 100644 (file)
@@ -743,6 +743,24 @@ append_ast_ext_slice(_PyUnicodeWriter *writer, slice_ty slice)
     return 0;
 }
 
+static int
+append_ast_index_slice(_PyUnicodeWriter *writer, slice_ty slice)
+{
+    int level = PR_TUPLE;
+    expr_ty value = slice->v.Index.value;
+    if (value->kind == Tuple_kind) {
+        for (Py_ssize_t i = 0; i < asdl_seq_LEN(value->v.Tuple.elts); i++) {
+            expr_ty element = asdl_seq_GET(value->v.Tuple.elts, i);
+            if (element->kind == Starred_kind) {
+                ++level;
+                break;
+            }
+        }
+    }
+    APPEND_EXPR(value, level);
+    return 0;
+}
+
 static int
 append_ast_slice(_PyUnicodeWriter *writer, slice_ty slice)
 {
@@ -752,8 +770,7 @@ append_ast_slice(_PyUnicodeWriter *writer, slice_ty slice)
     case ExtSlice_kind:
         return append_ast_ext_slice(writer, slice);
     case Index_kind:
-        APPEND_EXPR(slice->v.Index.value, PR_TUPLE);
-        return 0;
+        return append_ast_index_slice(writer, slice);
     default:
         PyErr_SetString(PyExc_SystemError,
                         "unexpected slice kind");