Python 2.7.10: Using LAMBDA and LOGICAL operators in DICT to choose a case

You could implement it like this:

def switcher(cases, default_func=None):
    def switch(value):
        for case_func, result in cases:
            if case_func(value):
                return result(value)

        if default_func is not None:
            return default_func(value)
        else:
            raise RuntimeError("No case matched and no default given")

    return switch

Usable as

my_switch = switcher([
    (lambda value: value == nBins, maxBucket),
    (lambda value: value < nBins, defaultBucket),
])

my_switch(val)

Leave a Comment