Python and PEP8 - Recommendations on breaking up long lines?

Nick Mellor thebalancepro at gmail.com
Wed Dec 4 20:47:01 EST 2013


Hi Victor,

I use PyCharm which is set up by default to warn when line length exceeds 120 chars, not 80. Perhaps times have changed?

I often break comprehensions at the for, in and else clauses. It's often not for line length reasons but because it's easier to follow the code that way. I have heard this is how Haskell programmers tend to use comprehensions (comprehensions are from Haskell originally):

location=random.choice([loc['pk']                                 
                        for loc                                   
                        in locations.whole_register()             
                        if loc['fields']['provider_id'] == provider_id])))

The other suggestion I have is to put the with clauses in a generator function. This saves you a level or more of indentation and modularises the code usefully. Here's an example:

def spreadsheet(csv_filename):
    with open(csv_filename) as csv_file:
        for csv_row in list(csv.DictReader(csv_file, delimiter='\t')):
            yield csv_row

then invoked using:

for row in spreadsheet("...")
    # your processing code here

Cheers,

Nick



More information about the Python-list mailing list