Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PEP 8 and list comprehension

Tags:

python

I seem to have hit a bit of a problem with PEP 8.

I am using list comprehension which is longer than 79 characters long. So my text editor is screaming at me to do something about it, and it's an eye soar to look at when coding.

enter image description here

return [(i['user_id'], i['id']) for i in j['collection'] if i and i['user_id']]

So, I attempt to break the line, but now it complains my line break is for visual purposes.

enter image description here

return [(i['user_id'], i['id']) for i in j['collection']
    if i and i['user_id']]

What's a man to do in such a pickle?

Edit: Based on the answers, I opted for readability over list comprehension in this case, and now it makes more sense to the reader:

tracks = set()

for track in json['collection']:
    if track and track['user_id']:
        tracks.add((track['user_id'], track['id']))
like image 576
James Jeffery Avatar asked May 06 '15 00:05

James Jeffery


People also ask

What is PEP 8 and why is it important?

PEP 8, sometimes spelled PEP8 or PEP-8, is a document that provides guidelines and best practices on how to write Python code. It was written in 2001 by Guido van Rossum, Barry Warsaw, and Nick Coghlan. The primary focus of PEP 8 is to improve the readability and consistency of Python code.

What is the difference between list comprehension and generator?

The only difference between Generator Comprehension and List Comprehension is that the former uses parentheses.

What is the difference between list comprehension and lambda?

The difference between Lambda and List Comprehension. List Comprehension is used to create lists, Lambda is function that can process like other functions and thus return values or lists.


2 Answers

if you want to stick strictly to pep8 then the hanging indent is your friend.

return [
    (i['user_id'], i['id'])
    for i in j['collection']
    if i and i['user_id']]
like image 162
Barry Rogerson Avatar answered Sep 28 '22 04:09

Barry Rogerson


You just need to indent the second line properly:

return [(i['user_id'], i['id']) for i in j['collection']
        if i and i['user_id']]

Confirmed with PEP8 online, but let me know whether it works for you as well.

Personally, I dislike expression and source together but the condition separate. I'd rather clearly see the expression alone, not the condition. Highlight what you get. So I would do one of these:

return [(i['user_id'], i['id'])
        for i in j['collection'] if i and i['user_id']]

return [(i['user_id'], i['id'])
        for i in j['collection']
        if i and i['user_id']]

Clarification: This is how I'd indent/break. I didn't consider the variable names, as I just wanted to give a direct answer and explain what the PEP8 error was and how to fix it, because noone else had.

like image 45
Stefan Pochmann Avatar answered Sep 28 '22 05:09

Stefan Pochmann