class _Precedence:
"""Precedence table that originated from python grammar."""
- TUPLE = auto()
+ NAMED_EXPR = auto() # <target> := <expr1>
+ TUPLE = auto() # <expr1>, <expr2>
YIELD = auto() # 'yield', 'yield from'
TEST = auto() # 'if'-'else', 'lambda'
OR = auto() # 'or'
self.traverse(node.value)
def visit_NamedExpr(self, node):
- with self.require_parens(_Precedence.TUPLE, node):
+ with self.require_parens(_Precedence.NAMED_EXPR, node):
self.set_precedence(_Precedence.ATOM, node.target, node.value)
self.traverse(node.target)
self.write(" := ")
def visit_Assign(self, node):
self.fill()
for target in node.targets:
+ self.set_precedence(_Precedence.TUPLE, target)
self.traverse(target)
self.write(" = ")
self.traverse(node.value)
def _for_helper(self, fill, node):
self.fill(fill)
+ self.set_precedence(_Precedence.TUPLE, node.target)
self.traverse(node.target)
self.write(" in ")
self.traverse(node.iter)
)
def visit_Tuple(self, node):
- with self.delimit("(", ")"):
+ with self.require_parens(_Precedence.TUPLE, node):
self.items_view(self.traverse, node.elts)
unop = {"Invert": "~", "Not": "not", "UAdd": "+", "USub": "-"}
def test_precedence_enum(self):
class _Precedence(enum.IntEnum):
"""Precedence table that originated from python grammar."""
- TUPLE = enum.auto()
+ NAMED_EXPR = enum.auto() # <target> := <expr1>
+ TUPLE = enum.auto() # <expr1>, <expr2>
YIELD = enum.auto() # 'yield', 'yield from'
TEST = enum.auto() # 'if'-'else', 'lambda'
OR = enum.auto() # 'or'
self.check_src_roundtrip("lambda x, y, /, z, q, *, u: None")
self.check_src_roundtrip("lambda x, *y, **z: None")
+ def test_star_expr_assign_target(self):
+ for source_type, source in [
+ ("single assignment", "{target} = foo"),
+ ("multiple assignment", "{target} = {target} = bar"),
+ ("for loop", "for {target} in foo:\n pass"),
+ ("async for loop", "async for {target} in foo:\n pass")
+ ]:
+ for target in [
+ "a",
+ "a,",
+ "a, b",
+ "a, *b, c",
+ "a, (b, c), d",
+ "a, (b, c, d), *e",
+ "a, (b, *c, d), e",
+ "a, (b, *c, (d, e), f), g",
+ "[a]",
+ "[a, b]",
+ "[a, *b, c]",
+ "[a, [b, c], d]",
+ "[a, [b, c, d], *e]",
+ "[a, [b, *c, d], e]",
+ "[a, [b, *c, [d, e], f], g]",
+ "a, [b, c], d",
+ "[a, b, (c, d), (e, f)]",
+ "a, b, [*c], d, e"
+ ]:
+ with self.subTest(source_type=source_type, target=target):
+ self.check_src_roundtrip(source.format(target=target))
+
+ def test_star_expr_assign_target_multiple(self):
+ self.check_src_roundtrip("a = b = c = d")
+ self.check_src_roundtrip("a, b = c, d = e, f = g")
+ self.check_src_roundtrip("[a, b] = [c, d] = [e, f] = g")
+ self.check_src_roundtrip("a, b = [c, d] = e, f = g")
+
+
class DirectoryTestCase(ASTTestCase):
"""Test roundtrip behaviour on all files in Lib and Lib/test."""
--- /dev/null
+:func:`ast.unparse` will now drop the redundant parentheses when tuples used
+as assignment targets (e.g in for loops).