#1
  1. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Posts
    206
    Rep Power
    12

    lambda for two statements


    Hi all,

    I have a dictionary like the following:
    Code:
    bla = {float: lambda a, b: a.asString(b),          # case 1
             int:    lambda a, b, c: a.asString(b,c)    # case 2
            }
    But now in the first case I want to add something like:
    Code:
    a.round()
    The return value of that statement is Null.

    Is it possible to integrate that statement somehow in the lambda function?

    Regards,

    Wizard2003
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Feb 2004
    Location
    London, England
    Posts
    1,585
    Rep Power
    1373
    You could do

    Code:
    lambda a, b: a.round() or a.asString(b)
    Since a.round() always returns Null, the or operator will go on and execute the second part of the statement.

    IMHO this is not very readable though, since the purpose of the or is not obvious.

    Another way would be to put the result of each call into an array or tuple and then return the last one:

    Code:
    lambda a, b: ( a.round(), a.asString(b) )[-1]
    Again this is not very readable, but has the advantage that it will still work if the first function returns a True value. It be made more readable by wrapping it up in a function:

    Code:
    def do_each(*vals): return vals[-1]
    
    lambda a, b: do_each( a.round(), a.asString(b) )
    The disadvantage of the last two is that the order of evaluation is not guaranteed by the language - a.asString(b) could be evaluated before a.round(). In the current implementation it is always evaluated left to right as you would expect, but that could change in future implementations.

    Dave - The Developers' Coach

IMN logo majestic logo threadwatch logo seochat tools logo