python3: accessing the result of 'if'

Carl Banks invalidemail at
Sat Jan 8 21:06:23 EST 2005

Nick Coghlan wrote:
> I have a different suggestion for this.
> 'as' is used for renaming in import statements. 'as' will be used for
> naming in Python 3k.
> So let's use it for expression naming in 'if' statements, too.
> if someregexp.match(s) as m:
>    # blah using m
> elif someotherregexp.match(s) as m:
>    # blah using m

What if the condition you wanted to test wasn't the same as the thing
you want to save?  In other words, how would you convert this?

. where:
.     m = something()
. if m > 20:
.     do_something_with(m)

What you propose works for typical regexps idiom but not for the
slightly more general case.  However, I could see why some people might
not like the where...if syntax I proposed; it's kind of choppy and not
exactly easy to follow at a first glance.

As a compromise, howabout:

. if m > 20 where m=something():
.     do_something_with(m)

In this case, the m=something() is NOT an assignment statement, but
merely a syntax resembling it.  The "where m=something()" is part of
the if-statement, not the if-expression.  It causes m to be visisble in
the if-expression and the if-block.

It (or your suggestion) could work with a while-loop too.

. while line where line=f.readline():
.     do_something_with(line)

The main problem here (as some would see it) is that you can't do
something this:

. if m > 20 where (def m(): a(); b()):


More information about the Python-list mailing list