TumblrPulse

Your Window to Inspiration: Seamlessly Browse Tumblr!

Switch - Blog Posts

4 years ago

An epistle on an “oh duh” moment I just had while pondering switch functionality in Python.

Every couple of months when I get back into some hobbyist Python development I find myself DuckDuckGo-ing “switch in Python” and am subsequently always reminded that that’s not explicitly a thing. You, of course, get that functionality from dictionaries.

I’ve always thought that was dumb, but today I was considering it and realized that it’s all because of the interpreted nature of the language. Switch statements have the wicked performance improvements over if ladders in compiled languages because the switch tells the compiler to put a bunch of branches in the intermediate assembly so a lot of unnecessary condition checks are skipped.

Without in-depth knowledge of how the interpreter works, it now becomes clear why you have to use the dictionary. It’s not the Python lords being pretentious and imposing their pythonic ways; you have to be more explicit to the interpreter about where to look for the logic to run because the interpreter doesn’t craft intermediate assembly, it just plows straight through. So a switch in Python would ultimately perform no better than an if ladder.

That doesn’t mean a switch wouldn’t make me happy, mind you.


Tags
Loading...
End of content
No more pages to load
Explore Tumblr Blog
Search Through Tumblr Tags