[Python-ideas] if with as

Talin talin at acm.org
Sat Mar 3 19:50:46 CET 2007


Armin Ronacher wrote:
> Hi all,
> 
> Many languages allow assignment expressions in if conditions. (Perl, PHP, Ruby,
> C, etc..) I know that this was dismissed by guido because it can lead to
> mistakes. And i can support that. However in some situations it might be
> required because you have to nest if blocks and regular expressions for example::
> 
>     while pos < text_length:
>         if match = name_re.match(text, pos):
>             pos = match.end()
>             do_something(match)
>         elif match = digit_re.match(text, pos):
>             pos = match.end()
>             do_something(match)
>         else:
>             pos += 1
> 
> Well. But that would require an assignment. Why not use the "as" keyword
> introduced in python2.5 with the future import::
> 
>     while pos < text_length:
>         if name_re.match(text, pos) as match:
>             pos = match.end()
>             do_something(match)
>         elif digit_re.match(text, pos) as match:
>             pos = match.end()
>             do_something(match)
>         else:
>             pos += 1
> 
> Advantages: Still no assignment expression, no additional keyword, simple to
> understand.

Personally, I like it - it's an issue that I've brought up before, but 
your syntax is better. With the introduction of 2.5's "with A as B", and 
the new exception-handling syntax in Py3K 'except E as v' (and the 
already existing import syntax), it seems to me that we are, in fact, 
establishing a general rule that:

	<keyword> <expression> as <variable>:

...is a common syntactical pattern in Python, meaning 'do something 
special with expression, and then as a side effect, assign that 
expression to the named variable for this block."

-- Talin



More information about the Python-ideas mailing list