Skip to content

bpo-40663: Correctly generate annotations for subscripts #20156

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 18, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Lib/test/test_future.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,9 @@ def test_annotations(self):
eq("dict[str, int]")
eq("set[str,]")
eq("tuple[str, ...]")
eq("tuple[(str, *types)]")
eq("tuple[str, int, (str, int)]")
Copy link
Member

@pablogsal pablogsal May 18, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This case was passing before. Did you meant tuple[str, int, *(str, int)]?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is for validating tuples have parens when they are inside of another tuple with different precedence.

eq("tuple[(*int, str, str, (str, int))]")
eq("tuple[str, int, float, dict[str, int]]")
eq("slice[0]")
eq("slice[0:1]")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Correctly generate annotations where parentheses are omitted but required
(e.g: ``Type[(str, int, *other))]``.
13 changes: 12 additions & 1 deletion Python/ast_unparse.c
Original file line number Diff line number Diff line change
Expand Up @@ -781,8 +781,19 @@ static int
append_ast_subscript(_PyUnicodeWriter *writer, expr_ty e)
{
APPEND_EXPR(e->v.Subscript.value, PR_ATOM);
int level = PR_TUPLE;
expr_ty slice = e->v.Subscript.slice;
if (slice->kind == Tuple_kind) {
for (Py_ssize_t i = 0; i < asdl_seq_LEN(slice->v.Tuple.elts); i++) {
expr_ty element = asdl_seq_GET(slice->v.Tuple.elts, i);
if (element->kind == Starred_kind) {
++level;
break;
}
}
}
APPEND_STR("[");
APPEND_EXPR(e->v.Subscript.slice, PR_TUPLE);
APPEND_EXPR(e->v.Subscript.slice, level);
APPEND_STR_FINISH("]");
}

Expand Down