How do you format list comprehensions that are too long and go beyond the line width?

What to do when you have a list comprehension that is too long?

When it comes to formatting, there are three ways to go about it:

  1. Don't worry with code formatting *at all.
  2. Applying a consistent (personal) style.
  3. Letting an auto-formatter do the heavy lifting.

In my opinion, you shouldn't be in category 1. As I have written before, code style matters. As for categories 2. and 3., you can do whatever you want.

I do both:

  • I use black to format my code consistently; but
  • I try to write my code already in the style that black likes.

For list comprehensions, I think it looks pretty nifty:

# ๐Ÿคฎ
def some_function(...):
    while True:
        with open(...) as really_long_file_name_variable:
            beginnings = [this_is_a_line[:10] for this_is_a_line in really_long_file_name_variable]
            # This list comprehension is waaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaay too long -^

# โšซโœจ
def some_function(...):
    while True:
        with open(...) as really_long_file_name_variable:
            beginnings = [
                this_is_a_line[:10]
                for this_is_a_line in really_long_file_name_variable
            ]

When a list comprehension is too long, black splits it:

  • the opening bracket [ stays right where it is;
  • the main expression goes on a new line by itself and is indentend with respect to the line where the [ is;
  • the loop goes on a new line by itself and aligned with the main expression; and
  • the closing bracket ] goes in a new line, with the indentation of the line where the [ is.

If there are more loops or if there are conditions, they all get their own lines:

# ๐Ÿคฎ
[final for sub1 in iterable if condition1(sub1) for sub2 in sub1 if condition2(sub2) for final in sub2]

# โšซโœจ
[
    final
    for sub1 in iterable
    if condition1(sub1)
    for sub2 in sub1
    if condition2(sub2)
    for final in sub2
]

# This is a terrible list comprehension...
# I'm just showing how formatting works ๐Ÿคฃ

Now you know what to do with a long list comprehension!

This article was generated automatically from this thread I published on Twitter @mathsppblog. Then it was edited lightly.

Thanks for reading โค๏ธ

I hope you learned something new! If you did, consider following the footsteps of the readers who bought me a slice of pizza ๐Ÿ•. Your contribution boosts my confidence and helps me produce this content for you.

Previous Post Next Post

Blog Comments powered by Disqus.