[OK, so rather than wait another two years before I write anything original on this blog, I’m just going to post interesting links that deal with things I’ve been thinking about. ]

So one odd programming construct that is ubiquitous, yet absent from Python, is the “switch” statement, meant to save a stream of if-else statements. In languages like JavaScript, C++, and Java, they would look something like this:

    case 1: 
        return one();
    case 2:
        return two();
        throw Exception("Not a valid number");

Python doesn’t have this, but there are many ways to do it with a dictionary. Something like:

switch_dict = {    
    1: one,
    2: two,

func = switch_dict.get(number)
if not func:
    raise Exception("Not a valid number")
return func()

But to compare the different methodologies, I’d really recommend checking out this post by Yong Cui. He compares the different ways to approach this pattern, along with the most efficient choices for your work.

Tagged with:

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Set your Twitter account name in your settings to use the TwitterBar Section.