[Python-ideas] "While" suggestion

Ron Adam rrr at ronadam.com
Wed Jul 9 16:49:36 CEST 2008

Terry Reedy wrote:

> Your specific example is so regular that it also could be written 
> (better in my opinion) as a for loop by separating what varies from what 
> does not:
> match_tok = (
>   (re_comment, TOK_COMMENT),
>   (re_indent, TOK_INDENT),
>    ...
>   (re_string, TOK_STRING),
> )
> # if <re_x> is actually re.compile(x), then tokens get bundled with
> # matchers as they are compiled.  This strikes me as good.
> for matcher,tok in match_tok:
>   m = matcher.match(s)
>   if m:
>     process(tok, m.group(1)
>     break
> else:
>   raise InvalidTokenError(s)
> Notice how nicely Python's rather unique for-else clause handles the 
> default case.
> Terry Jan Reedy

This is the same solution I came up with.  It separates the data from the 
code in a way that is much easier to read and maintain.

Any time I see more than 3 elif's or else's, It's a hint for me to look for 
a more generalized solution like this.


More information about the Python-ideas mailing list