On Tue, 10 Nov 2009 20:13:21 -0800, Carl Banks wrote: > On Nov 10, 7:12 pm, Steven D'Aprano > <ste...@remove.this.cybersource.com.au> wrote: >> On Tue, 10 Nov 2009 12:45:13 -0800, Bearophile wrote: >> > r: >> >> >> i think the following syntax would be quite beneficial to replace >> >> some redundant "if's" in python code. >> >> >http://python.org/dev/peps/pep-3003/ >> >> I knew it wouldn't take long for people to start responding to any >> proposal with "don't bother, there's a moratorium". >> >> Of course in this case, the correct response would have been "don't >> bother, it's a stupid idea, moratorium or no moratorium". > > r didn't actually give a good example. Here is case where it's actually > useful. (Pretend the regexps are too complicated to be parsed with > string method.) > > if re.match(r'go\s+(north|south|east|west)',cmd) as m: > hero.move(m.group(1)) > elif re.match(r'take\s+(\w+)',cmd) as m: > hero.pick_up(m.group(1)) > elif re.match(r'drop\s+(\w+)',cmd) as m: > here.put_Down(m.group(1))
This is where a helper function is good. You want a dispatcher: COMMANDS = { r'go\s+(north|south|east|west)': hero.move, r'take\s+(\w+)': hero.pick_up, r'drop\s+(\w+)': here.put_Down, } def dispatch(cmd): for regex in COMMANDS: m = re.match(regex, cmd) if m: COMMANDS[regex](m.group(1)) break dispatch(cmd) If you need the regexes to be tested in a specific order, change the dict to an OrderedDict, or use a list of tuples and the obvious change to the for loop. -- Steven -- http://mail.python.org/mailman/listinfo/python-list