Return value of an assignment statement?

Carl Banks pavlovevidence at gmail.com
Fri Feb 22 10:04:17 CET 2008


On Feb 21, 4:57 pm, mrstephengross <mrstevegr... at gmail.com> wrote:
> > What you can't do (that I really miss) is have a tree of assign-and-test
> > expressions:
> >         import re
> >         pat = re.compile('some pattern')
> >         if m = pat.match(some_string):
> >             do_something(m)
>
> Yep, this is exactly what I am (was) trying to do. Oh well.... Any
> clever ideas on this front?


Yeah, I got something clever.  I don't recommend using it, biut


def call_if_true(cond):
    if cond:
        return lambda func: func(cond)
    return lambda func: None


@call_if_true(re.match(r"name=(.*)"))
def set_name(m):
    name = m.group(1).strip()

@call_if_true(re.match(r"id=(.*)"))
def set_id(m):
    id = m.group(1).strip()

@call_if_true(re.match(r"phone=(.*)"))
def set_phone(m):
    phone = m.group(1).strip()



This decorator might be more to the point:

def call_if_match(regexp):
    m = re.match(regexp)
    if m:
        return lambda func: func(m)
    return lambda func: None



These have the drawback of being a little dense, and the functions
can't rebind variables in the caller's local namespace, but it is
clever.

P.S. I don't recommend using it.


Carl Banks



More information about the Python-list mailing list