Skip to content

Commit 25fa13f

Browse files
committed
Fix parsing trailing comma after for loop index variables
Fixes #543.
1 parent 8992bb8 commit 25fa13f

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

mypy/parse.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -875,6 +875,7 @@ def parse_for_stmt(self) -> ForStmt:
875875
def parse_for_index_variables(self) -> Node:
876876
# Parse index variables of a 'for' statement.
877877
index_items = List[Node]()
878+
force_tuple = False
878879

879880
while True:
880881
v = self.parse_expression(precedence['in'],
@@ -883,8 +884,11 @@ def parse_for_index_variables(self) -> Node:
883884
if self.current_str() != ',':
884885
break
885886
self.skip()
887+
if self.current_str() == 'in':
888+
force_tuple = True
889+
break
886890

887-
if len(index_items) == 1:
891+
if len(index_items) == 1 and not force_tuple:
888892
index = index_items[0]
889893
else:
890894
index = TupleExpr(index_items)

mypy/test/data/parse.test

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1503,6 +1503,44 @@ MypyFile:1(
15031503
Block:1(
15041504
PassStmt:2())))
15051505

1506+
[case testForAndTrailingCommaAfterIndexVar]
1507+
for i, in x:
1508+
pass
1509+
[out]
1510+
MypyFile:1(
1511+
ForStmt:1(
1512+
TupleExpr:1(
1513+
NameExpr(i))
1514+
NameExpr(x)
1515+
Block:1(
1516+
PassStmt:2())))
1517+
1518+
[case testListComprehensionAndTrailingCommaAfterIndexVar]
1519+
x = [a for b, in c]
1520+
[out]
1521+
MypyFile:1(
1522+
AssignmentStmt:1(
1523+
NameExpr(x)
1524+
ListComprehension:1(
1525+
GeneratorExpr:1(
1526+
NameExpr(a)
1527+
TupleExpr:1(
1528+
NameExpr(b))
1529+
NameExpr(c)))))
1530+
1531+
[case testForAndTrailingCommaAfterIndexVars]
1532+
for i, j, in x:
1533+
pass
1534+
[out]
1535+
MypyFile:1(
1536+
ForStmt:1(
1537+
TupleExpr:1(
1538+
NameExpr(i)
1539+
NameExpr(j))
1540+
NameExpr(x)
1541+
Block:1(
1542+
PassStmt:2())))
1543+
15061544
[case testGeneratorWithCondition]
15071545
x for y in z if 0
15081546
[out]

0 commit comments

Comments
 (0)