Beginners' Question -- Assigning variables in a lambda

Tim Rowe digitig at cix.co.uk
Fri May 26 13:58:00 EDT 2000


Are beginners' questions ok here? (if not, where?)

After I've done my getopt (or maybe instead, if I can get this to work) I 
want to avoid the if/elif/else from hell by having a dictionary of 
parameter names and functions, something like:

   handler = {
      # Doesn't work!
      "b": lambda x: eval("bandwidth = get_number(" + x + ")")
      # , ... more here ...
      }
      
(get_number is essentially string.atof with some special handling)
then later on do, for example:
   handler["b"]("0.23")

and I'd like to call eval("bandwidth = get_number(0.23)") (it seems to get 
that far) and so assign 0.23 to bandwidth (it won't do that bit!)

I suspect my problem is that I need to exec("bandwidth = get_number(" + x 
+ ")"), but lambda won't take exec.

Is there a sensible way to do what I'm tying to do?

TIA.



More information about the Python-list mailing list