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.
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.
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']))
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.
The only difference between Generator Comprehension and List Comprehension is that the former uses parentheses.
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.
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']]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With