python3: accessing the result of 'if'

Steve Holden steve at holdenweb.com
Sun Jan 9 10:45:58 EST 2005


Nick Coghlan wrote:

> 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!"
> 

Excuse me, these are supposed to be IMPROVEMENTS to Python?

regards
  Steve
-- 
Steve Holden               http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
Holden Web LLC      +1 703 861 4237  +1 800 494 3119



More information about the Python-list mailing list