Skip to content

Commit 950ec38

Browse files
Disallow unwrapping tuples in an as clause (#4634)
1 parent 2c135ed commit 950ec38

File tree

4 files changed

+25
-0
lines changed

4 files changed

+25
-0
lines changed

Diff for: CHANGES.md

+2
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@
1313
- Fix crash while formatting expressions using the walrus operator in complex
1414
`with` statements (#4630)
1515
- Handle `# fmt: skip` followed by a comment at the end of file (#4635)
16+
- Fix crash when a tuple appears in the `as` clause of a `with` statement
17+
(#4634)
1618

1719
### Preview style
1820

Diff for: src/black/linegen.py

+2
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@
5656
is_rpar_token,
5757
is_stub_body,
5858
is_stub_suite,
59+
is_tuple,
5960
is_tuple_containing_star,
6061
is_tuple_containing_walrus,
6162
is_type_ignore_comment_string,
@@ -1626,6 +1627,7 @@ def maybe_make_parens_invisible_in_atom(
16261627
node.type not in (syms.atom, syms.expr)
16271628
or is_empty_tuple(node)
16281629
or is_one_tuple(node)
1630+
or (is_tuple(node) and parent.type == syms.asexpr_test)
16291631
or (is_yield(node) and parent.type != syms.expr_stmt)
16301632
or (
16311633
# This condition tries to prevent removing non-optional brackets

Diff for: src/black/nodes.py

+11
Original file line numberDiff line numberDiff line change
@@ -603,6 +603,17 @@ def is_one_tuple(node: LN) -> bool:
603603
)
604604

605605

606+
def is_tuple(node: LN) -> bool:
607+
"""Return True if `node` holds a tuple."""
608+
if node.type != syms.atom:
609+
return False
610+
gexp = unwrap_singleton_parenthesis(node)
611+
if gexp is None or gexp.type != syms.testlist_gexp:
612+
return False
613+
614+
return True
615+
616+
606617
def is_tuple_containing_walrus(node: LN) -> bool:
607618
"""Return True if `node` holds a tuple that contains a walrus operator."""
608619
if node.type != syms.atom:

Diff for: tests/data/cases/context_managers_39.py

+10
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,11 @@ async def func():
8484
pass
8585

8686

87+
88+
# don't remove the brackets here, it changes the meaning of the code.
89+
with (x, y) as z:
90+
pass
91+
8792
# output
8893

8994

@@ -172,3 +177,8 @@ async def func():
172177
some_other_function(argument1, argument2, argument3="some_value"),
173178
):
174179
pass
180+
181+
182+
# don't remove the brackets here, it changes the meaning of the code.
183+
with (x, y) as z:
184+
pass

0 commit comments

Comments
 (0)