In the := operator is very easy to get wrong and accidentally forget the (. Having black adding brace would clarify what get's assigned.
Example of desired behavior:
if x := y op z: # Before
if x := (y op z): # After
# And no changes in the following cases
if x := y: # Before
if x := y: # After (no change)
if (x := y) op z: # Before
if (x := y) op z: # After (no change)
Examples:
while pos := buffer.find(search_term, pos + 1) >= 0: # Before
while pos := (buffer.find(search_term, pos + 1) >= 0): # After < Expose a bug in the code !
if match := pattern.match(line): # Before
if match := pattern.match(line): # After (no change)
if attr := sys.modules.get('attr') and attr.has(type(obj): # Before
if attr := (sys.modules.get('attr') and attr.has(type(obj)): # After < Expose a bug in the code !!
if (attr := sys.modules.get('attr')) and attr.has(type(obj): # Before
if (attr := sys.modules.get('attr')) and attr.has(type(obj): # After (no change)
It’s been proposed to just always require parentheses around an assignment expression. This would resolve many ambiguities, and indeed parentheses will frequently be needed to extract the desired subexpression.
Even if at the parser level, it's ok to not use brace, I think at the formatting level, adding brace would greatly clarify what is assigned. Especially considering the walrus is a quite "advanced" operator.
I started using walrus and regularly got bugs in my code due to forgetting to add braces.
Black already add () on some operations to help readibility, like:
x = x, # Before
x = (x,) # After
I think braces around the walrus operator would greatly help readability and avoid bugs.
In the
:=
operator is very easy to get wrong and accidentally forget the(
. Having black adding brace would clarify what get's assigned.Example of desired behavior:
Examples:
Adding parenthesis around walrus was even concidered in the original PEP to resolve ambiguity https://peps.python.org/pep-0572/#always-requiring-parentheses
Even if at the parser level, it's ok to not use brace, I think at the formatting level, adding brace would greatly clarify what is assigned. Especially considering the
walrus
is a quite "advanced" operator.I started using walrus and regularly got bugs in my code due to forgetting to add braces.
Black already add
()
on some operations to help readibility, like:I think braces around the
walrus
operator would greatly help readability and avoid bugs.