Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #62995

Re: Ifs and assignments

Date 2014-01-02 09:46 -0800
From Ethan Furman <ethan@stoneleaf.us>
Subject Re: Ifs and assignments
References <52C59FF6.5000607@allsup.co>
Newsgroups comp.lang.python
Message-ID <mailman.4804.1388687545.18130.python-list@python.org> (permalink)

Show all headers | View raw


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~

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Ifs and assignments Ethan Furman <ethan@stoneleaf.us> - 2014-01-02 09:46 -0800

csiph-web