[Python-Dev] PEP 7 clarification request: braces

Ron Adam ron3200 at gmail.com
Mon Jan 2 07:22:05 CET 2012


On Mon, 2012-01-02 at 14:44 +1000, 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.

I've had to correct my self on this one a few times so I will have to
agree it's a good practice.

> (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)

The problem is only when an additional statement is added to the last
block, not the preceding ones, as the compiler will complain about
those.  So I don't know how the 4 line example without braces is any
worse than a 2 line if without braces.

I think my preference is, if any block in a multi-block expression needs
braces, then the other blocks should have it.  (Including the last block
even if it's a single line.)

The next level up would be to require them on all blocks, even two line
if expressions, but I'm not sure that is really needed.  At some point
the extra noise of the braces makes things harder to read rather than
easier, and what you gain in preventing one type of error may increase
chances of another type of error not being noticed.

Cheers,
   Ron



> 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.




More information about the Python-Dev mailing list