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

Stefan Behnel stefan_ml at behnel.de
Mon Jun 5 03:14:12 EDT 2017


Serhiy Storchaka schrieb am 03.06.2017 um 18:25:
> Yet about braces. PEP 7 implicitly forbids breaking the line before an
> opening brace. An opening brace should stay at the end the line of the
> outer compound statement.
> 
>     if (mro != NULL) {
>         ...
>     }
>     else {
>         ...
>     }
> 
>     if (type->tp_dictoffset != 0 && base->tp_dictoffset == 0 &&
>         type->tp_dictoffset == b_size &&
>         (size_t)t_size == b_size + sizeof(PyObject *)) {
>         return 0; /* "Forgive" adding a __dict__ only */
>     }
> 
> But the latter example continuation lines are intended at the same level as
> the following block of code. I propose to make exception for that case and
> allow moving an open brace to the start of the next line.
> 
>     if (type->tp_dictoffset != 0 && base->tp_dictoffset == 0 &&
>         type->tp_dictoffset == b_size &&
>         (size_t)t_size == b_size + sizeof(PyObject *))
>     {
>         return 0; /* "Forgive" adding a __dict__ only */
>     }
> 
> This adds a visual separation of a multiline condition from the following
> code.

Python itself has a similar problem and solves it differently. Why not take
a look at PEP-8 here?

"""
Yes:

# Aligned with opening delimiter.
foo = long_function_name(var_one, var_two,
                         var_three, var_four)

# More indentation included to distinguish this from the rest.
def long_function_name(
        var_one, var_two, var_three,
        var_four):
    print(var_one)

# Hanging indents should add a level.
foo = long_function_name(
    var_one, var_two,
    var_three, var_four)

No:

# Arguments on first line forbidden when not using vertical alignment.
foo = long_function_name(var_one, var_two,
    var_three, var_four)

# Further indentation required as indentation is not distinguishable.
def long_function_name(
    var_one, var_two, var_three,
    var_four):
    print(var_one)
"""

ISTM that overindenting the conditions (i.e. following the "more
indentation" example) solves this problem and makes it very readable. The
same can be done in C code and avoids having to remember two different
special ways to do it for core devs in C and Python.

Stefan



More information about the Python-Dev mailing list