pythonline-breaks

Is it possible to break a long line to multiple lines in Python?


Just like C, you can break a long line into multiple short lines. But in Python, if I do this, there will be an indent error... Is it possible?


Solution

  • From PEP 8 - Style Guide for Python Code:

    The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. If necessary, you can add an extra pair of parentheses around an expression, but sometimes using a backslash looks better. Make sure to indent the continued line appropriately.

    Example of implicit line continuation:

    a = (
        '1'
        + '2'
        + '3'
        - '4'
    )
    
    
    b = some_function(
        param1=foo(
            "a", "b", "c"
        ),
        param2=bar("d"),
    )
    

    On the topic of line breaks around a binary operator, it goes on to say:

    For decades the recommended style was to break after binary operators. But this can hurt readability in two ways: the operators tend to get scattered across different columns on the screen, and each operator is moved away from its operand and onto the previous line.

    In Python code, it is permissible to break before or after a binary operator, as long as the convention is consistent locally. For new code Knuth's style (line breaks before the operator) is suggested.

    Example of explicit line continuation:

    a = '1'   \
        + '2' \
        + '3' \
        - '4'