Ifs and assignments

Tim Chase python.list at tim.thechases.com
Thu Jan 2 17:08:23 EST 2014


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






More information about the Python-list mailing list