PyCQA / pycodestyle

Simple Python style checker in one Python file
https://pycodestyle.pycqa.org
Other
5.01k stars 755 forks source link

E251: keyword `=` vs. expressions with spaces #1240

Closed adamsol closed 4 months ago

adamsol commented 4 months ago

Sometimes I see a code like this:

f(x=a * b)

Or a more real-life example with Django:

Order.objects.filter(timestamp__gt=timezone.now() - timedelta(minutes=30))

Though this formatting seems to be in accordance with PEP8, it always strikes me as illogical and hard to read, as the spacing contradicts the operator precedence, with the LHS being glued to the parameter name.

In cases like this, I tend to introduce an additional variable or at least add parentheses around the expression. However, it's difficult to ensure this approach within a team without linter's help.

To further analyse the situation:


What is pycodestyle's recommendation on this subject?

Would it be feasible to implement one of the following solutions?

A. Introduce a rule to detect and report whitespace usage that contradicts operator precedence. User could then manually assign the expression to a variable: x = a * b; f(x=x), add parentheses around it: f(x=(a * b)), or just remove spaces around the operator: f(x=a*b). The rule could also detect poor formatting in other contexts, like x+a * b.

B. Introduce a rule to always require spaces around the equals sign: f(x = a * b), which would violate PEP8, but allow for a more consistent (and arguably more readable) code style. It's worth noting that spaces around = for default arguments is the standard convention in other popular programming languages, like JavaScript, C++, C#.

asottile commented 4 months ago

this isn't changing, this would break too many things plus I don't agree with you that whitespace should follow operator precedence