while expression feature proposal

D

Dan Loewenherz

Hi all,

This is my first post to this group--I'm not subscribed, so please CC
me in responses.

So I'm sure a lot of you have run into the following pattern. I use it
all the time and it always has felt a bit awkward due to the duplicate
variable assignment.

VAR = EXPR
while VAR:
BLOCK
VAR = EXPR

I'm curious what the possibility of adding the following to Python as
syntactic sugar:

while EXPR as VAR:
BLOCK

Apologies if that has been proposed before. I searched the archives
and couldn't find any mention of it.

Best,
Dan
 
P

Paul Rubin

Dan Loewenherz said:
VAR = EXPR
while VAR:
BLOCK
VAR = EXPR

for VAR in iter(lambda: EXPR, None):
BLOCK

where the termination sentinel might be False or '' or whatever instead
of None. Of course if EXPR is a callable, there's no lambda.
while EXPR as VAR:
BLOCK

This is kind of nice. I wonder if it could generalize "with" somehow,
i.e. use the context manager for EXPR if it has one. Or maybe "iter"
could be generalized so you could pass an arbutrary predicate as
termination condition, instead of a single sentinel value.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top