Yesterday I came up with a very interesting syntax idea, after chatting about it with some friends I’ve decided to ask whether or not it can be implemented. Obviously I’m probably going to do something wrong, but I hope my post gets me on the right track.
The point of my syntax idea would be to allow breaking and finishing a generator expression if a condition is met, here’s an example:
items = [i for i in range(10) while i < 5]
print(items) # [0, 1, 2, 3, 4]
That example could probably be done with if i < 5
, however here’s another one that gives a better idea of what this might be able to do:
items = [1, 2, 3, 4, "5", 6, 7, 8, 9]
var = [i for i in items if isinstance(i, int)]
print(var) # [1, 2, 3, 4, 6, 7, 8, 9]
var = [i for i in items while isinstance(i, int)]
print(var) # [1, 2, 3, 4]
The expanded version of this generator might look something like this:
items = [1, 2, 3, 4, "5", 6, 7, 8, 9]
var = []
for i in items:
if not isinstance(i, int):
break
var.append(i)
I’m aware of itertools.takewhile
, I just think it might be better to have this as a syntax feature instead.