[Python-Dev] PEP 7 clarification request: braces

Ned Batchelder ned at nedbatchelder.com
Mon Jan 2 15:10:40 CET 2012


On 1/1/2012 11:44 PM, Nick Coghlan wrote:
> I've been having an occasional argument with Benjamin regarding braces
> in 4-line if statements:
>
>    if (cond)
>      statement;
>    else
>      statement;
>
> vs.
>
>    if (cond) {
>      statement;
>    } else {
>      statement;
>    }
>
> 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)
>
> Since Benjamin doesn't accept the current brace example in PEP 7 as
> normative for the case above, I'm bringing it up here to seek
> clarification.
I've always valued readability and consistency above brevity, and Python 
does too.  *Sometimes* using braces in C is a recipe for confusion, and 
only adds to the cognitive load in reading the code.  The examples 
elsewhere in this thread of mistakes and noisy diffs due to leaving out 
the braces are plenty of reason for me to always include braces.

The current code uses a mixture of styles, but that doesn't mean we need 
to allow any style in the future.  I'm in favor of PEP 7 being amended 
to either require or strongly favor the braces-always style.  Note: 
while we're reading the tea-leaves in PEP 7, it has an example of a 
single-line if clause with no braces.

Some people favor the braces-sometimes style because it leads to 
"lighter" code.  I think that's a misguided optimization.  Consistency 
is better than reducing the line count.

--Ned.
> Cheers,
> Nick.
>


More information about the Python-Dev mailing list