Search code examples
python-3.xformattingpep8

How to make a line break on . notation in accordance to PEP8


So according to PEP8 a line in python shouldn't be any longer than 79 characters, and for some lines, only 72 characters. Now I've been running into this problem a lot lately, and normally it's not to hard to fix. For example say I have some code like this:

x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...]
# Convert it to this (I'm too lazy to indent it sry)
x = [1,
2,
3,
4,
5,
6,
7,
8,
9,
1,
2,
3,
4,
5,
6,
7,
8,
9]

Now this isn't the problem. The problem arises when I have a . function.

For example this:

f'Some long f-string that's almost 79 characters...'.encode()

Now I could break the string but that makes it look very un clean, and hard to read, especially if it has embedded if or for statements in the f-string.

I've been doing this but I'm not sure if it's the right thing to do.

f'f-string that's long...'\
.encode()

So essentially I'm not sure if that's how to do it or I do something else.

Now also I've wondered how I'm supposed to properly indent strings that span multiple lines, because if I try and keep a common indentation, the string will get a huge indent.

For example:

x = '''Multi
       Line
       String'''

print(x)

Prints:

Multi
       Line
       String

So how do I format it so it looks nice, and works properly?


Solution

  • Excerpt from PEP-8 in Maximum Line Length:

    The preferred way of wrapping long lines is by using Python’s implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.

    So following the suggestion, I would place the method call on the line following the f-string, and enclose the expression in parentheses:

    s = (
        f"1 + 1 == {1 + 1}..."
        f'1 - 1 == {1 - 1}'
        .encode()
    )
    print(s)
    

    This outputs:

    b'1 + 1 == 2...1 - 1 == 0'
    

    Regarding indenting a multi-line string represented in a triple-quoted docstring, you can follow the example shown in the documentation of textwrap.dedent to indent all lines normally (but add a backslash after the first triple quote to avoid producing a newline character), and let dedent remove common leading spaces for you:

    from textwrap import dedent
    
    s = dedent('''\
        Multi
        Line
        String''')
    print(s)
    

    This outputs:

    Multi
    Line
    String