[Python-Dev] PEP 7 and braces { .... } on if

Serhiy Storchaka storchaka at gmail.com
Wed May 31 12:02:57 EDT 2017


31.05.17 17:11, Victor Stinner пише:
> I have a question on the CPython coding code for C code, the PEP 7:
> https://www.python.org/dev/peps/pep-0007/
> 
> """
> Code structure: (...); braces are strongly preferred but may be
> omitted where C permits, and they should be formatted as shown:
> 
> if (mro != NULL) {
>      ...
> }
> else {
>      ...
> }
> """
> 
> This section was updated after the creation of CPython in 1991, so as
> you may expect, a lot of existing C code doesn't respect this coding
> style. I'm trying to slowly add "missing" braces and indent as the
> example *when I have to modify existing code*.
> 
> The problem is the "strongly preferred" and "omitted where C permits"
> part. I would like to make the PEP 7 more explicit on that part since
> in each review, I disagree with Serhiy who wants to omit them.
> Example:
> 
> if (func == NULL)
>      return NULL;
> 
> versus
> 
> if (func == NULL) {
>      return NULL;
> }
> 
> I now prefer the version with braces. It's more verbose, but it
> prevents bugs when the code is modified later for whatever reasons.
> IMHO it also makes the code easily to read and to understand.
> 
> So I would suggest to modify the PEP 7 to *always* require braces for if.
> 
> I would also suggest to require braces on "for(...) { ... }" and
> "while(...) { ... }". But only if the code has to be modified, not
> only to update the coding style.

Thank you for opening this discussion Victor. I was going to open it myself.

I strongly prefer using braces around "for" and "while" bodies. I 
dislike unconditional adding braces, but after changing PEP 7 I became 
always adding them in my code and asking this in reviewed code. I even 
made Argument Clinic generating braces around gotos. But when I asked 
Barry to add braces around simple statements to satisfy PEP 7 
requirements, he pointed out that braces are only "strongly preferred". 
Since that time I allowed myself to left braces out in cases when they 
look cluttering.

I think that PEP 7 should be more explicit about cases in what braces 
are required and in what they are optional. I prefer to make them 
optional (or even make the variant without braces preferable) in case of 
"if" (without "else") or "case" body containing only the single "goto", 
"break", "continue" or simple "return". Especially if it follows by an 
empty line or closing brace. Adding braces in these cases decreases 
readability IMHO. This is one peculiarity for which many people like (or 
hate) Python.



More information about the Python-Dev mailing list