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


Groups > comp.lang.python > #63001 > unrolled thread

Re: Ifs and assignments

Started byTim Chase <python.list@tim.thechases.com>
First post2014-01-02 16:08 -0600
Last post2014-01-02 16:08 -0600
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Ifs and assignments Tim Chase <python.list@tim.thechases.com> - 2014-01-02 16:08 -0600

#63001 — Re: Ifs and assignments

FromTim Chase <python.list@tim.thechases.com>
Date2014-01-02 16:08 -0600
SubjectRe: Ifs and assignments
Message-ID<mailman.4809.1388700455.18130.python-list@python.org>
On 2014-01-02 17:20, John Allsup wrote:
> m = r1.search(w)
> if m:
> 	handleMatch1(m)
> else:
> 	m = r2.search(w)
> 	if m:
> 		handleMatch2(m)
> 	else:
> 		print("No match")
> 
> if not running unnecessary matches, yet capturing groups in the
> event of a successful match, is what is desired.
> 
> If there are multiple tests, the indentation gets silly.  This
> arises because having removed the ability to assign in an
> expression, there is no way to save the result of a function call
> that is used in a conditional at all.

Usually this is done something like

  pairs = (
  for r, fn in (
      (r1, handleMatch1),
      (r2, handleMatch2),
      (r3, handleMatch3),
      ):
    m = r.search(w)
    if m:
      fn(m)
      break
  else: # yes, a for/else, a handy Python construct if new to you
    print("No match")

which simplifies the logic considerably, avoiding the deep nesting.

-tkc


[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web