Python list comprehensions and the with keyword

Give me with or give me death

Clark DuVall
2 min readMay 26, 2014

Python is my favorite language. I like writing Python, I like reading Python. Language features like decorators, meta classes, context managers, list/set/dict comprehensions, etc. all make Python so much fun to write. That’s why it makes me sad when I can’t use these things when I really, really want to.

I have run into the problem multiple times where I want to use a list comprehension for something like this:

stripped_words = [word.strip() for word in words if word.strip()]

But no one wants to run .strip() on a word twice, so I then shed a tear and rewrite as:

stripped_words = []
for word in words:
stripped_word = word.strip()
if stripped_word:
stripped_words.append(stripped_word)

Not only is this slower, but it’s ugly and offends my delicate Python sensibilities. What I want is a “with” keyword in comprehensions that allows you to assign variables in the scope of the comprehension, similar to Haskell’s local let declarations in list comprehensions. So then my word stripper could be written like this:

stripped_words = [stripped_word for word in words if stripped_word
with stripped_word=word.strip()]

Ah, how beautiful that is. Now I can go back to writing my Python like Python, and not splitting what should be a simple list comprehension into a 5 line for loop.

--

--