Skip to content

Commit 2c0f1e7

Browse files
mtc-mlxzzzeek
authored andcommitted
Support nested tuple unpacking in for loops
Fixed issue where unpacking nested tuples in a for loop using would raise a "couldn't apply loop context" error if the loop context was used. The regex used to match the for loop expression now allows the list of loop variables to contain parenthesized sub-tuples. Pull request courtesy Matt Trescott. For example: ~~~ for (key1, val1), (key2, val2) in itertools.pairwise(dict.items()): ... ~~~ This is really just "kicking the can down the road" so to speak, because it doesn't allow an infinite number of layers of tuples, but it helps somewhat. Closes: #368 Pull-request: #368 Pull-request-sha: 3f15a87 Change-Id: I52915acb8904daf7071d8c92e1de352f200131ec
1 parent 0c4e737 commit 2c0f1e7

3 files changed

Lines changed: 26 additions & 2 deletions

File tree

doc/build/unreleased/368.rst

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
.. change::
2+
:tags: bug, codegen
3+
:tickets: 368
4+
5+
Fixed issue where unpacking nested tuples in a for loop using would raise a
6+
"couldn't apply loop context" error if the loop context was used. The regex
7+
used to match the for loop expression now allows the list of loop variables
8+
to contain parenthesized sub-tuples. Pull request courtesy Matt Trescott.
9+

mako/codegen.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1251,8 +1251,13 @@ def visitCallTag(self, node):
12511251

12521252

12531253
_FOR_LOOP = re.compile(
1254-
r"^for\s+((?:\(?)\s*[A-Za-z_][A-Za-z_0-9]*"
1255-
r"(?:\s*,\s*(?:[A-Za-z_][A-Za-z0-9_]*),??)*\s*(?:\)?))\s+in\s+(.*):"
1254+
r"^for\s+((?:\(?)\s*"
1255+
r"(?:\(?)\s*[A-Za-z_][A-Za-z_0-9]*"
1256+
r"(?:\s*,\s*(?:[A-Za-z_][A-Za-z_0-9]*),??)*\s*(?:\)?)"
1257+
r"(?:\s*,\s*(?:"
1258+
r"(?:\(?)\s*[A-Za-z_][A-Za-z_0-9]*"
1259+
r"(?:\s*,\s*(?:[A-Za-z_][A-Za-z_0-9]*),??)*\s*(?:\)?)"
1260+
r"),??)*\s*(?:\)?))\s+in\s+(.*):"
12561261
)
12571262

12581263

test/test_loop.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,16 @@ def test__FOR_LOOP(self):
3131
"x",
3232
"[y+1 for y in [1, 2, 3]]",
3333
),
34+
(
35+
"for ((key1, val1), (key2, val2)) in pairwise(dict.items()):",
36+
"((key1, val1), (key2, val2))",
37+
"pairwise(dict.items())",
38+
),
39+
(
40+
"for (key1, val1), (key2, val2) in pairwise(dict.items()):",
41+
"(key1, val1), (key2, val2)",
42+
"pairwise(dict.items())",
43+
),
3444
):
3545
match = _FOR_LOOP.match(statement)
3646
assert match and match.groups() == (target_list, expression_list)

0 commit comments

Comments
 (0)