Python and PEP8 - Recommendations on breaking up long lines?

Ben Finney ben+python at benfinney.id.au
Wed Nov 27 21:55:10 EST 2013


Victor Hooi <victorhooi at gmail.com> writes:

>     cur.executemany("INSERT INTO foobar_foobar_files VALUES (?)",
>                     [[os.path.relpath(filename, foobar_input_folder)] for filename in filenames])
>
> I've already broken it up using the parentheses

But now the continuation line indentation is needlessly dependent on the
content of the previous line.

Better to just use a standard additional indentation (I prefer 8 columns
to easily distinguish from block indentation) for any continuation
line::

    cur.executemany(
            "INSERT INTO foobar_foobar_files VALUES (?)", [
                [os.path.relpath(filename, foobar_input_folder)]
                for filename in filenames])

Notice that further continuation within an existing continuation doesn't
get another 8, but only another 4 columns. The whole statement is
already distinguished, I don't need to add huge amounts of further
indentation for that purpose.

>     if os.path.join(root, file) not in previously_processed_files and os.path.join(root, file)[:-3] not in previously_processed_files:

In cases where the line is long because of a long expression, enclosing
that expression in parens for clarification will then give you an easy
way to break for continuation lines::

    if (
            os.path.join(root, file) not in previously_processed_files
            and os.path.join(root, file)[:-3] not in previously_processed_files):

But that's still some long lines, and your repeated use of a computed
value is an ideal opportunity to bind it to a convenience name for local
use::

    file_path = os.path.join(root, file)
    if (
            file_path not in previously_processed_files
            and file_path[:-3] not in previously_processed_files):

Not least because you're very likely going to use the value of
‘file_path’ yet again in the body of that ‘if’ block.

-- 
 \         “Two paradoxes are better than one; they may even suggest a |
  `\                                         solution.” —Edward Teller |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list