1

I had to add extraneous parens to a while condition today to avoid pep8 complaints:

while not found and not something and \
    (time_left is None or time_left > 0):
    (one, two, three, four) = self.gimme(timeout=time_left)

My solution:

while (not found and not something and
       (time_left is None or time_left > 0)):
    (one, two, three, four) = self.gimme(timeout=time_left)

If I changed the 2nd line indent, it complained of over-indent or missing indent, for every indent from even with the W in while, to 8 to the right of it.

I'm bothered that adding extraneous parens to satisfy pep8, for little readability improvement, goes against general principles.

Any ideas? Have I missed a better solution?

Quantum Mechanic
  • 625
  • 1
  • 6
  • 20
  • 2
    PEP-8 recommends using parentheses over backslash continuation because the latter is more fragile: a single stray space after the backslash kills it. I agree that the extra parentheses do add a little more visual clutter, but you get used to it. ;) The extra spaces inside the parenthesized condition are legal, and I agree it's annoying if your IDE or linter complains about it; OTOH, I think it looks neater if the continued code is indented by one indentation level (typically 4 spaces). – PM 2Ring Jul 24 '17 at 17:11
  • 2
    Initially I had left an answer, but I'm starting to think that this is going to lead to a lot of opinionated answers without a real concrete "best" approach to do this, as it depends on taste. – Makoto Jul 24 '17 at 17:13
  • There are a variety of coding styles for Python. Many of them are supported by [YAPF](https://github.com/google/yapf#formatting-style), although I don’t think it supports preferring continuation over parentheses. – Daniel H Jul 24 '17 at 17:23

2 Answers2

6

I prefer to break the long lines after conditional statements to increase readability. e.g.:

while (
    not found and 
    not something and 
    (time_left is None or time_left > 9)
):
    (one, two, three, four) = self.gimme(timeout=time_left)

I think that is very readable and at least satisfies my pep8 codestyle check.

kofrezo
  • 61
  • 1
  • 1
    +1 and if you're using grumpy-ole-pylint it'll suggest an additional indent inside the condition to separate it visually from the code in the while block – anthony sottile Jul 24 '17 at 17:16
  • I tend to do something like this with my Perl, though I prefer (there) to have the boolean operator at the beginning, with a suitable indent for visual clarity. Of course, it doesn't work well for Python's significant whitespace. – Quantum Mechanic Jul 25 '17 at 10:37
0

I think the best solution is to do whatever you (and your team, if applicable) considers to be the most readable solution. PEP8 is just a guideline, it isn't a requirement. Focus on writing code that is robust and easy to comprehend.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685