Scott, in your “Functional Python” introduction you write:
The one limitation that most disappoints me is that Python lacks is a functional way of writing if/else. Sometimes you just want to do something like this:
lambda x : if_else(x>100, “big number”, “little number”)(This would return the string “big number” if x was greater than 100, and “little number” otherwise.) Sometimes I get around this by defining my own if_else that I can use in lambda-functions:
def if_else(condition, a, b) : if condition : return a else : return b
Actually, you don’t need this helper if_else function at all:
In [1]: f = lambda x: x > 100 and 'big' or 'small'
In [2]: for i in (1, 10, 99, 100, 101, 110): ...: print i, 'is', f(i) ...: 1 is small 10 is small 99 is small 100 is small 101 is big 110 is big
James, obviously you’re right… Stupid me didn’t think about that. Your version won’t work when a discriminator isn’t known at import time. But even then a function taking *args and **kwargs with a class-like name, returning a correct class instance, would cut the job.
Regarding the module/plugin stuff, I’d rather use setuptools/pkg_resources ![]()














11 Responses to “Python if/else in lambda”
Leave a comment