PEP 8 and list comprehension

后端 未结 4 1886
小鲜肉
小鲜肉 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 18:42

    When using pep8 common sense applies. If you can't fit a line of logic within 80 character it is almost always a sign that this line has to be rewritten. And it is true in this case as I can't for one even start to try to comprehend what is that line supposed to do.

    But if you move it to a much more readable format then not only your line count will go up, but also your readability level, leaving you a lot of place for proper variable names like user instead of i. This will make your own maintenance in the future much easier, not to mention if someone else ever have to look at it.

    So to put this example into actual code, that is what I would do with it (with a nice function wrap to make the sample much easier to read!):

    j = {'collection': [{'id': 1, 'user_id': 1}]}
    
    def get_qualified_users(users):
        qualified_users = []
        for user in users:
            if user and user['user_id']:
                qualified_users.append((user['user_id'], user['id']))
        return qualified_users
    
    print(get_qualified_users(j['collection']))
    

    You can easily copy/paste it into your interpetor to see that it works. And more than that - it is extremely easy to maintain and follow, with clear api encapsulated in a sealed function.

提交回复
热议问题