python3: accessing the result of 'if'

Nick Coghlan ncoghlan at iinet.net.au
Sun Jan 9 06:17:17 CET 2005


Carl Banks wrote:
> What if the condition you wanted to test wasn't the same as the thing
> you want to save?  In other words, how would you convert this?
> 
> . where:
> .     m = something()
> . if m > 20:
> .     do_something_with(m)

Yeah, this problem eventually occurred to me as well. However, I think a little 
utility function can help solve it:

   def test(val, condition):
     if condition(val):
       return val
      else:
       return None

   if test(something(), lambda x: x < 10) as m:
     print "Case 1:", m
   elif test(something(), lambda x: x > 20) as m:
     print "Case 2:", m
   else:
     print "No case at all!"

If we were to use a where clause instead, it looks like:

   if test(something(), less_than(10)) as m:
     print "Case 1:", m
   elif test(something(), more_than(20)) as m:
     print "Case 2:", m
   else:
     print "No case at all!"
   where:
     def less_than(y):
       def lt(x):
         return x < y
       return lt

     def more_than(y):
       def gt(x):
         return x > y
       return lt

This is an example of why I don't think where clauses would completely eliminate 
the utility of deferred expressions. Here's a version using my preferred syntax 
from the AlternateLambdaSyntax page:

   if test(something(), (def x < 10 from x)) as m:
     print "Case 1:", m
   elif test(something(), (def x > 20 from x)) as m:
     print "Case 2:", m
   else:
     print "No case at all!"

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at email.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.skystorm.net



More information about the Python-list mailing list