PEP 8 and list comprehension

后端 未结 4 1889
小鲜肉
小鲜肉 2021-01-17 18:27

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 s

4条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-17 19:02

    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.

提交回复
热议问题