How to indent Python list-comprehensions?

前端 未结 7 1507
失恋的感觉
失恋的感觉 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:58

    How about:

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

    Generally, long lines can be avoided by pre-computing subexpressions into variables, which might add a minuscule performance cost:

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

    By the way, isn't 'is not False' kind-of superfluous ? Are you worried about differentiating between None and False ? Because otherwise, it suffices to leave the condition as only: if (x.type == "post" and x.deleted)

提交回复
热议问题