while expression feature proposal

Thomas Rachel nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de
Thu Oct 25 05:44:33 EDT 2012


Am 25.10.2012 00:26 schrieb Cameron Simpson:

> If I could write this as:
>
>    if re_FUNKYPATTERN.match(test_string) as m:
>      do stuff with the results of the match, using "m"
>
> then some cascading parse decisions would feel a bit cleaner. Where I
> current have this:
>
>    m = re_CONSTRUCT1.match(line)
>    if m:
>      ... handle construct 1 ...
>    else:
>      m = re_CONSTRUCT2.match(line)
>      if m:
>        ... handle construct 2 ...
>      else:
>        m = re_CONSTRUCT3.match(line)
>
> I could have this:
>
>    if re_CONSTRUCT1.match(line) as m:
>      ... handle construct 1 ...
>    elif re_CONSTRUCT2.match(line) as m:
>      ... handle construct 2 ...
>    elif re_CONSTRUCT3.match(line) as m:

I would do

     for r in re_CONSTRUCT1, re_CONSTRUCT2, re_CONSTRUCT3:
         m = r.match(line)
         if m: handle_construct

or maybe

     actions = {re_CONSTRUCT1: action1, ...}

     def matching(line, *rr):
         for r in rr:
             m = r.match(line)
             if m: yield r; return

     for r in matching(line, *actions.keys()):
         actions[r]()
         break
     else:
         raise NoActionMatched() # or something like that

Thomas



More information about the Python-list mailing list