Search code examples
pythoncoding-style

How to indent Python list-comprehensions?


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?

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

Solution

  • 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.