C-like assignment expression?
Bruno Desthuilliers
bruno.42.desthuilliers at websiteburo.invalid
Wed May 21 07:14:38 EDT 2008
boblatest at googlemail.com a écrit :
> Hello,
>
> I have an if-elif chain in which I'd like to match a string against
> several regular expressions. Also I'd like to use the match groups
> within the respective elif... block. The C-like idiom that I would
> like to use is this:
>
> if (match = my_re1.match(line):
> # use match
> elsif (match = my_re2.match(line)):
> # use match
> elsif (match = my_re3.match(line))
> # use match
<ot>
Isn't it the third or fourth time this very same question pops up here ?
Starts to look like a FAQ.
</ot>
The canonical solution is to iterate over a list of expression,function
pairs, ie:
def use_match1(match):
# code here
def use_match2(match):
# code here
def use_match3(match):
# code here
for exp, func in [
(my_re1, use_match1),
(my_re2, use_match2),
(my_re3, use_match3)
]:
match = exp.match(line)
if match:
func(match)
break
The alternate solution is Diez's Test object.
HTH
More information about the Python-list
mailing list