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:
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:
black
to format my code consistently; butblack
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:
[
stays right where it is;[
is;]
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.
+35 chapters. +400 pages. Hundreds of examples. Over 30,000 readers!
My book “Pydon'ts” teaches you how to write elegant, expressive, and Pythonic code, to help you become a better developer. >>> Download it here 🐍🚀.