[Python-Dev] PEP 7 clarification request: braces

"Martin v. Löwis" martin at v.loewis.de
Tue Jan 3 09:44:03 CET 2012


> He keeps leaving them out, I occasionally tell him they should always
> be included (most recently this came up when we gave conflicting
> advice to a patch contributor). He says what he's doing is OK, because
> he doesn't consider the example in PEP 7 as explicitly disallowing it,
> I think it's a recipe for future maintenance hassles when someone adds
> a second statement to one of the clauses but doesn't add the braces.
> (The only time I consider it reasonable to leave out the braces is for
> one liner if statements, where there's no else clause at all)

While this appears to be settled, I'd like to add that I sided with
Benjamin here all along.

With Python, I accepted a style of "minimal punctuation". Examples
of extra punctuation are:
- parens around expression in Python's if (and while):

    if (x < 10):
      foo ()

- parens around return expression (C and Python)

    return(*p);

- braces around single-statement blocks in C

In all these cases, punctuation can be left out without changing
the meaning of the program.

I personally think that a policy requiring braces would be (mildly)
harmful, as it decreases readability of the code. When I read code,
I read every character: not just the identifiers, but also every
punctuation character. If there is extra punctuation, I stop and wonder
what the motivation for the punctuation is - is there any hidden
meaning that required the author to put the punctuation?

There is a single case where I can accept extra punctuation in C:
to make the operator precedence explicit. Many people (including
myself) don't know how

   a | b << *c * *d

would group, so I readily accept extra parens as a clarification.

Wrt. braces, I don't share the concern that there is a risk of
somebody being confused when adding a second statement to a braceless
block. An actual risk is stuff like

   if (cond)
     MACRO(argument);

when MACRO expands to multiple statements. However, we should
accept that this is a bug in MACRO (which should have used the
do-while(0)-idiom), not in the application of the macro.

Regards,
Martin


More information about the Python-Dev mailing list