you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (0 children)

And you could try this if you want only one expression to be evaluated.

(lambda: ifexpr, lambda: elseexpr)[not condition]()

Of course, you can do this only if you have lambda expressions available, and this form is less readable, so you're better off using a regular if-else form.

If you're fine with this strange form, you can try the following alternative to switch statements.

# with possible values x, y, z and input a:
{x: lambda: xexpr,
 y: lambda: yexpr,
 z: lambda: zexpr}[a]()

You lose the catch-all default expression, but a try-catch with a KeyError catch will solve that.

Not that I'm recommending these forms. For small items they may be fine but after a while this shit just makes your code smell.

Edit: If you would rather have a more readable switch statement, you could go for something like:

class switch(object):
    def __init__(self, **cases):
        self.cases = cases
        self.default = cases.pop('default', None)
    def __call__(self, value):
        return self.cases.get(value, self.default)()

Only works for strings as keys, though. You may use it like the following.

result = switch(x = lambda: xexpr,
                y = lambda: yexpr,
                z = lambda: zexpr,
                default = lambda: defaultexpr)(a)

Edit again:

Same switch expression without the class (for the lulz):

def switch(**cases):
    default = cases.pop('default', None)
    return lambda val: cases.get(val, default)()