C-like assignment expression?

Diez B. Roggisch deets at nospam.web.de
Wed May 21 05:46:48 EDT 2008


boblatest at googlemail.com wrote:

> 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
> 
> ...buy this is illegal in python. The other way is to open up an else:
> block in each level, do the assignment and then the test. This
> unneccessarily leads to deeper and deeper nesting levels which I find
> ugly. Just as ugly as first testing against the RE in the elif: clause
> and then, if it matches, to re-evaluate the RE to access the match
> groups.

This might help:

-----------
s = "foo"

class Tester(object):

    def __call__(self, pattern):
        self.m = re.match(pattern, s)
        return self.m is not None

    def __getattr__(self, name):
        return getattr(self.m, name)

test = Tester()

if test("bar"):
    print "wrong"
elif test("foo"):
    print "right"
-------------


Diez



More information about the Python-list mailing list