Aviv Roth
“Switch” statements in Python
[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:
switch(number):
case 1:
return one();
break;
case 2:
return two();
break;
default:
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.
Recent Comments
- JPEREZGIL on REST calls in .NET (C#) over SSL (HTTPS)
- Reivaj810 on REST calls in .NET (C#) over SSL (HTTPS)
- Juancastein on Installing SharePoint 2013 on Windows Server 2012 R2 Preview
- Juancastein on Installing SharePoint 2013 on Windows Server 2012 R2 Preview
- Arjen Holterman on REST calls in .NET (C#) over SSL (HTTPS)
Categories