psf / black

The uncompromising Python code formatter
https://black.readthedocs.io/en/stable/
MIT License
38.37k stars 2.42k forks source link

Add parenthesis around walrus #4058

Open Conchylicultor opened 9 months ago

Conchylicultor commented 9 months ago

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)

Adding parenthesis around walrus was even concidered in the original PEP to resolve ambiguity https://peps.python.org/pep-0572/#always-requiring-parentheses

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.

JelleZijlstra commented 9 months ago

Could you give some examples of cases where we should add parentheses?

Conchylicultor commented 9 months ago

Sorry, the issue got created while I was still writing. Updated the issue with examples