Python and PEP8 - Recommendations on breaking up long lines?

Ned Batchelder ned at nedbatchelder.com
Thu Nov 28 04:05:21 CET 2013


On 11/27/13 9:03 PM, Victor Hooi wrote:
> 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.

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

>
> and:
>
>                      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)...

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

This has the advantage of naming these complex intermediate conditions, 
and giving you natural places to write comments explaining them.  Why 
[:-3] for example?

More, shorter, statements.

--Ned.

>
> Cheers,
> Victor
>





More information about the Python-list mailing list