Ifs and assignments

Chris Angelico rosuav at gmail.com
Thu Jan 2 19:06:05 EST 2014


On Fri, Jan 3, 2014 at 10:36 AM, Roy Smith <roy at panix.com> wrote:
> The most common place I wish for an atomic "test and assign" is with
> regexes, as in your examples.  This would be so much nicer than what we
> have to do now:
>
>     if re.match(string) as m:
>         print m.group(0)

Here's a crazy idea. Suppose we have a "sticky falseness" that can
quietly propagate through an expression the way a NaN can... then we
could just float that right through the .group() call.

class truth:
    def __new__(cls, x):
        if x: return x
        return object.__new__(cls)
    def __bool__(self):
        return False
    def __getattr__(self, name):
        return self
    def __call__(self, *args, **kwargs):
        return self
    def __repr__(self):
        return repr(False)

Pass any object through truth() and it'll either stay the same (if
it's true) or become this object (if it's false). You can then carry
on with other method calls, and they'll all happily return false.

result = (
    truth(re1.match(string)).group(0) or
    truth(re2.match(string)).group(0) or
    truth(re3.match(string)).group(0) or
    default_value
)

(I'm not sure if I'm using __new__ correctly; I've never actually done
it in production code, and the info I found online was mainly Py2
examples. Should that be done with super(), or is that applicable only
once there's an actual instance with a real MRO?)

I've given the class a lower-case first letter as I'm basically using
this as a function. If this were ever to be considered for the
standard library I would expect to see that aspect of it heavily
bikeshedded, so I'm not too concerned about the details.

In a spirit of full disclosure, I must confess that the idea came from
Pike, where there's a variant member-lookup operator that will happily
return false from false rather than throwing an exception. :)

ChrisA



More information about the Python-list mailing list