Hacker News new | ask | show | jobs
by tclancy 2180 days ago
I came to Python after ~5 years of programming in C-style languages (about 15 years ago) and the lack of a switch statement may be the one thing about Python that demonstrably made me a better coder.

When I discovered there wasn't one, I was really annoyed and went digging for an explanation. The one I found was a suggestion if you are reaching for a switch statement, you're (probably) doing something wrong. This is not to impugn anyone else's approach or style and I will freely admit there are times when all you need is a switch and if/ else if/ else gets ugly, but most times I find the replacement for switch is not that but a dictionary holding a callable or similar. I recently showed this approach to a peer in PR and watching it click for her was awesome. She ripped out most of what she'd done and replaced some of our more ponderous permission checking with a dictionary of functions to apply.

I'd say the other thing I do when I wish I had a switch statement is realize I am writing code that is halfway to doing things The Right Way and refactor the block into smaller functions.

1 comments

Can you give an example? I've never heard of this recommendation and I have a bit of trouble imagining it in a way that is simpler than a bunch of if-else

I came up with the following, and that definitely doesn't convince me.

    def call_a():
        pass

    def call_b():
        pass

    def default_func():
        pass

    myswitch = {
        "a": call_a
        "b": call_b
    }

    myfunc = myswitch.get(x, default_func)
    myfunc()
vs

    if x == "a":
        pass
    elif x == "b":
        pass
    else:
        pass