How to indent Python list-comprehensions?

前端 未结 7 1261
失恋的感觉
失恋的感觉 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 07:05

    It depends on how long they are. I tend to structure them like so:

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

    That way every expression has its own line.

    If any line becomes too big I like to extract it out in a lambda or expression:

    transform = lambda x: x.id
    results = self.db.query(schema.allPostsUuid).execute(timeout=20)
    condition = lambda x: x.deleted is not False and ... and ...
    [transform(x) for x in results if condition(x)]
    

    And then if a lambda becomes too long it gets promoted to a function.

    0 讨论(0)
提交回复
热议问题