Disallow unwrapping tuples in an as clause (#4634)

This commit is contained in:
Tushar Sadhwani 2025-04-01 20:19:37 +05:30 committed by GitHub
parent 2c135edf37
commit 950ec38c11
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 25 additions and 0 deletions

View File

@ -13,6 +13,8 @@
- Fix crash while formatting expressions using the walrus operator in complex
`with` statements (#4630)
- Handle `# fmt: skip` followed by a comment at the end of file (#4635)
- Fix crash when a tuple appears in the `as` clause of a `with` statement
(#4634)
### Preview style

View File

@ -56,6 +56,7 @@
is_rpar_token,
is_stub_body,
is_stub_suite,
is_tuple,
is_tuple_containing_star,
is_tuple_containing_walrus,
is_type_ignore_comment_string,
@ -1626,6 +1627,7 @@ def maybe_make_parens_invisible_in_atom(
node.type not in (syms.atom, syms.expr)
or is_empty_tuple(node)
or is_one_tuple(node)
or (is_tuple(node) and parent.type == syms.asexpr_test)
or (is_yield(node) and parent.type != syms.expr_stmt)
or (
# This condition tries to prevent removing non-optional brackets

View File

@ -603,6 +603,17 @@ def is_one_tuple(node: LN) -> bool:
)
def is_tuple(node: LN) -> bool:
"""Return True if `node` holds a tuple."""
if node.type != syms.atom:
return False
gexp = unwrap_singleton_parenthesis(node)
if gexp is None or gexp.type != syms.testlist_gexp:
return False
return True
def is_tuple_containing_walrus(node: LN) -> bool:
"""Return True if `node` holds a tuple that contains a walrus operator."""
if node.type != syms.atom:

View File

@ -84,6 +84,11 @@ async def func():
pass
# don't remove the brackets here, it changes the meaning of the code.
with (x, y) as z:
pass
# output
@ -172,3 +177,8 @@ async def func():
some_other_function(argument1, argument2, argument3="some_value"),
):
pass
# don't remove the brackets here, it changes the meaning of the code.
with (x, y) as z:
pass