[Python-ideas] "While" suggestion
Talin
talin at acm.org
Tue Jul 8 04:10:49 CEST 2008
Guido van Rossum wrote:
> On Thu, Jul 3, 2008 at 8:21 PM, Fred Drake <fdrake at acm.org> wrote:
>> On Jul 3, 2008, at 10:58 PM, Raymond Hettinger wrote:
>>> I co-authored a PEP for a do-while construct and it died solely because we
>>> couldn't find a good pythonic syntax. The proposed while-as construct will
>>> neatly solve some of the use cases -- the rest will have to live with what
>>> we've got.
>> I actually like the "do: ... while <expr>: ..." syntax better.
>
> Same here. The while ... as ... syntax introduces a special case that
> doesn't handle enough cases to be worth the cost of a special case.
> Zen of Python: "Special cases aren't special enough to break the
> rules."
>
> To summarize why while...as... doesn't handle enough cases: it only
> works if the <setup> can be expressed a single assignment and the
> value assigned is also the value to be tested. Like it or not, many
> uses of assignment expressions in C take forms like these:
I'm actually more interested in the "as" clause being added to "if"
rather than "while". The specific use case I am thinking is matching
regular expressions, like so:
def match_token(s):
# Assume we have regex's precompiled for the various tokens:
if re_comment.match(s) as m:
# Do something with m
process(TOK_COMMENT, m.group(1))
elif re_ident.match(s) as m:
# Do something with m
process(TOK_IDENT, m.group(1))
elif re_integer.match(s) as m:
# Do something with m
process(TOK_INT, m.group(1))
elif re_float.match(s) as m:
# Do something with m
process(TOK_COMMENT, m.group(1))
elif re_string.match(s) as m:
# Do something with m
process(TOK_STRING, m.group(1))
else:
raise InvalidTokenError(s)
In other words, the general design pattern is one where you have a
series of tests, where each test can return either None, or an object
that you want to examine further. Of course, if it's just a single
if-statement, it's easy enough to assign the variable in one statement
and test in the next.
There are a number of workarounds, of course - put the tests in a
function and use return instead of elif; Use 'else' instead of elif and
put the subsequent 'if' in the else block (and deal with indentation
crawl) and so on. So it's not a huge deal, I'm just pointing out one
possible use case where it might make the code a bit prettier.
(Also, there's a much faster way to do the above example, which is to
smush all of the patterns into a single massive regex, and then check
the last group index of the match object to see which one matched.)
-- Talin
More information about the Python-ideas
mailing list