Skip to content

Commit

Permalink
Don't remove parens in asserts with assigment expr
Browse files Browse the repository at this point in the history
Black would previously strip the parenthesis away from assert statement like this one:

    assert (spam := 12 + 1)

Which happens to be invalid code. Now before making the parenthesis invisible, Black
checks if the assignment expression's parent is an assert stamtment, aborting if True.

I added a bunch of test cases from the PEP defining asssignment expressions (PEP 572).
  • Loading branch information
ichard26 committed Apr 26, 2021
1 parent 0a833b4 commit 4570dd5
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 1 deletion.
3 changes: 3 additions & 0 deletions CHANGES.md
Expand Up @@ -8,6 +8,9 @@
in the name of the cache file. Without this fix, changes in these flags would not take
effect if the cache had already been populated. (#2131)

- Don't remove necessary parentheses from assignment expression containing assert
statements. (#2143)

### 21.4b0

#### _Black_
Expand Down
2 changes: 1 addition & 1 deletion src/black/__init__.py
Expand Up @@ -5613,7 +5613,7 @@ def maybe_make_parens_invisible_in_atom(node: LN, parent: LN) -> bool:
return False

if is_walrus_assignment(node):
if parent.type in [syms.annassign, syms.expr_stmt]:
if parent.type in [syms.annassign, syms.expr_stmt, syms.assert_stmt]:
return False

first = node.children[0]
Expand Down
38 changes: 38 additions & 0 deletions tests/data/pep_572_remove_parens.py
Expand Up @@ -17,6 +17,25 @@

a, b = (test := (1, 2))

# see also https://github.com/psf/black/issues/2139
assert (foo := 42 - 12)

foo(x=(y := f(x)))


def foo(answer=(p := 42)):
...


def foo2(answer: (p := 42) = 5):
...


lambda: (x := 1)

# we don't touch expressions in f-strings but if we do one day, don't break 'em
f'{(x:=10)}'

# output
if foo := 0:
pass
Expand All @@ -36,3 +55,22 @@
test: int = (test2 := 2)

a, b = (test := (1, 2))

# see also https://github.com/psf/black/issues/2139
assert (foo := 42 - 12)

foo(x=(y := f(x)))


def foo(answer=(p := 42)):
...


def foo2(answer: (p := 42) = 5):
...


lambda: (x := 1)

# we don't touch expressions in f-strings but if we do one day, don't break 'em
f"{(x:=10)}"

0 comments on commit 4570dd5

Please sign in to comment.