Python and PEP8 - Recommendations on breaking up long lines?

Jussi Piitulainen jpiitula at ling.helsinki.fi
Thu Nov 28 07:12:43 CET 2013


Victor Hooi <victorhooi at gmail.com> writes:

> Hi,
> 
> Also, forgot two other examples that are causing me grief:
 
     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, not sure what's the
> tidy way to break it up again to fit under 80? In this case, the
> 80-character mark is hitting me around the "for filename" towards
> the end.

That's a natural break. I did it to your code above. Another is the
condition, if it's there:

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

There's much freedom of indentation inside the brackets, but these
points are natural.

> and:

Put the long expression in parentheses and you are again free to break
and indent; I tend to have extra spaces inside these parentheses, but
I have no idea about any standards:

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

> In this case, the 80-character mark is actually partway through
> "previously processed files" (the first occurrence)...

Try to find natural breaks, between phrases, and maybe highlight
operators by putting them in the beginning of a line like.

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



More information about the Python-list mailing list