C-like assignment expression?

Paul McGuire ptmcg at austin.rr.com
Sat May 24 09:42:56 EDT 2008


On May 21, 4:38 am, boblat... 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.
>
> Thanks,
> robert

Try this.

-- Paul

class TestValue(object):
    """Class to support assignment and test in single operation"""
    def __init__(self,v=None):
        self.value = v

    """Add support for quasi-assignment syntax using '<<' in place of
'='."""
    def __lshift__(self,other):
        self.value = other
        return bool(self.value)


import re

tv = TestValue()
integer = re.compile(r"[-+]?\d+")
real = re.compile(r"[-+]?\d*\.\d+")
word = re.compile(r"\w+")

for inputValue in ("123 abc 3.1".split()):
    if (tv << real.match(inputValue)):
        print "Real", float(tv.value.group())
    elif (tv << integer.match(inputValue)):
        print "Integer", int(tv.value.group())
    elif (tv << word.match(inputValue)):
        print "Word", tv.value.group()

Prints:

Integer 123
Word abc
Real 3.1





More information about the Python-list mailing list