Ifs and assignments

Ethan Furman ethan at stoneleaf.us
Thu Jan 2 12:46:52 EST 2014


On 01/02/2014 09:20 AM, John Allsup wrote:
>
> In many languages, such as C, one can use assignments in conditionals
> and expressions.  The most common, and useful case turns up when you
> have if/else if/else if/else constructs.  Consider the following
> non-working pseudoPython.
>
> import re
> r1 = re.compile("hello (\d)")
> r2 = re.compile("world([!?])")
>
> w = "hello world!"
>
> if m = r1.search(w):
>      handleMatch1(m)
> elif m = r2.search(w):
>      handleMatch2(m)
> else:
>      print("No match")

What you're looking for is a pocket function:

#untested
class assign(object):
     def set(self, value):
         self._assignment = value
         return value
     def get(self):
         return self._assignment

m = assign()

if m.set(r1.search(w)):
      handleMatch1(m.get())
elif m.set(r2.search(w)):
      handleMatch2(m.get())
else:
      print("No match")

--
~Ethan~



More information about the Python-list mailing list