How to check for redundant parentheses with flake8?

Question:

PyCharm has a nice feature that lints the following code

if (a == b):
    # ...

with “Remove redundant parentheses” concerning the (a == b) expression.

Running flake8 on the same code doesn’t complain about anything by default. Is it possible to configure flake8 in a way to detect unnecessary parentheses?

I have found this list of flake8 rules, but on first glance I cannot find a setting that might be related. If it is not possible with flake8, what does PyCharm use to perform this check?

Asked By: bluenote10

||

Answers:

Is switching to Pylint an option? The reason is that this rule:

superfluous-parens (C0325):
    Unnecessary parens after %r keyword Used when a single item in parentheses follows an if, for, or other keyword.

would address your issue.
Also, found this extension for Flake8:
https://gist.github.com/snoack/e78963516d93e55add32fc1f8237b0e4

Hope this helps, otherwise, don’t mind me.

Answered By: Konstantin Grigorov

Sadly, this check is not built into flake8. But due to its flexible plugin system, it’s not hard to add a plugin that performs said check.
Since I couldn’t find any plugin that does the job, I went ahead and, together with other people, created a plugin for flake8 that serves this exact purpose.

https://pypi.org/project/flake8-picky-parentheses

The used method is inspired by SebDieBln’s comment:
To figure out whether a pair of parentheses is redundant, try removing it and parsing the new code. If the parsing fails, they were necessary. If not, compare the ASTs of the original and the altered code. If they are the same, the code is semantically equivalent and the parentheses are redundant. On top of that, add some (maybe opinionated) exceptions where redundant parentheses help readability (e.g., a = (1, 2) or a = 1 + (n % 2)) and that’s it.

Answered By: Robsdedude
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.