1-line idiom to replace if blocks
Chad Netzer
cnetzer at mail.arc.nasa.gov
Fri Jan 24 16:29:54 EST 2003
On Friday 24 January 2003 09:10, Robin Munn wrote:
> # The idiom [false_val,true_val][condition] is equivalent to the
> # C idiom (condition ? true_val : false_val)...
> register_callback(1, lambda retval: ['Error','OK'][bool(retval)])
> register_callback(2, lambda retval: ['Error','OK'][bool(retval)])
> register_callback(3, lambda retval: ['Error','OK'][bool(retval)])
> register_callback(4, lambda retval: ['Error','OK'][bool(retval)])
> register_callback(5, lambda retval: ['Error','OK'][bool(retval)])
> register_callback(6, lambda retval: ['Error','OK'][bool(retval)])
I think this technique is valid, SOLELY because you preceeded it with
the comment that explains it's use. Given the line space you save
below, the extra lines used to comment the technique are almost
mandatory (ie. it may save you or someone else a few minutes of time in
the future.)
But having the idiom interspersed throughout code in random places is
likely to cause more troubles than it is worth, at least down the line
(there will be someone who wastes time figuring it out, more than was
ever saved using it piecemeal).
I think the general principal applies elsewhere. I've often used
lambda's not like the above, and the economy of expression made it
worth it, since I repeated many time in one place. But then you could
refactor the above code even further to have a callback factory, which
might even be clearer in the long run. (or just a single named function
for the specific case above, since all your callbacks do exactly the
same thing)
--
Bay Area Python Interest Group - http://www.baypiggies.net/
Chad Netzer
(any opinion expressed is my own and not NASA's or my employer's)
More information about the Python-list
mailing list