[Python-ideas] if with as

Josiah Carlson jcarlson at uci.edu
Sat Mar 3 10:40:01 CET 2007


Armin Ronacher <armin.ronacher at active-4.com> 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::
[snip]

You could convert the code you have offered into the following:

    while pos < text_length:
        match = name_re.match(text, pos) or \
                digit_re.match(text, pos) or \
                None
        if match:
            post = match.end()
            do_something(match)
        else:
            pos += 1

Not only does it work today in any Python with the re module, has the
same number of lines as what you provided, and doesn't repeat itself, it
can be shortened with a simple helper function.

-1

Also, I think it would be confusing.  It is currently used in imports
and the with statement, but it was *necessary* to have some assignment
semantic in with statement - there is no such necessity in if/elif (or
even while, which is the next step after if/elif).

 - Josiah




More information about the Python-ideas mailing list