pythonpep8

Does PEP 8 allow a simple hanging indent if it results in vertical alignment?


I am learning styling in Python and while reading PEP 8 I got confused with the following. According to PEP 8 if you use a hanging indent you should add more indentation to distinguish the arguments from the body of the function:

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

Then I found this code and wanted to ask you whether or not it is valid in this scenario that the condition is at the same indentation level as the rest. Should this be treated as hanging indent? Or since it is vertically aligned it is OK?

if (value1 == 0 and value2 == 0 and
    value3 == 'valueX' and value4 == 'valueY' or
    value5 > value6):
    raise ValueError("test")

Solution

  • On http://pep8online.com/ you can check code snippets for PEP8 compliance.

    If you paste this

    if (value1 == 0 and value2 == 0 and
        value3 == 'valueX' and value4 == 'valueY' or
        value5 > value6):
        raise ValueError("test")
    

    You will see that it gives the following

    E125 line 3 column 5: continuation line does not distinguish itself from next logical line

    Futher indenting line 3 (by 4 spaces) makes the error go away. Below code is valid, however weird it might look to the eye.

    if (value1 == 0 and value2 == 0 and
        value3 == 'valueX' and value4 == 'valueY' or
            value5 > value6):
        raise ValueError("test")
    

    It might be better readable like so, which is another valid solution:

    if (value1 == 0 and value2 == 0 and
            value3 == 'valueX' and value4 == 'valueY' or
            value5 > value6):
        raise ValueError("test")