How to indent Python list-comprehensions?

前端 未结 7 1277
失恋的感觉
失恋的感觉 2021-01-30 06:17

List comprehensions can be useful in certain situations, but they can also be rather horrible to read.. As a slightly exaggerated example, how would you indent the following?

7条回答
  •  北荒
    北荒 (楼主)
    2021-01-30 06:45

    You should not use a list comprehension for that.

    List comprehensions are an awesome feature, but they are meant to be shortcuts, not regular code.

    For such a long snippet, you should use ordinary blocs :

    allUuids = []
    for x in self.db.query(schema.allPostsUuid).execute(timeout = 20) :
        if x.type == "post" and x.deleted is not False :
            allUuids.append(x.id)
    

    Exactly the same behavior, much more readable. Guido would be proud of you :-)

提交回复
热议问题