Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any value to a Switch / Case implementation in Python?

Recently, I saw some discussions online about how there is no good "switch / case" equivalent in Python. I realize that there are several ways to do something similar - some with lambda, some with dictionaries. There have been other StackOverflow discussions about the alternatives. There were even two PEPs (PEP 0275 and PEP 3103) discussing (and rejecting) the integration of switch / case into the language.

I came up with what I think is an elegant way to do switch / case.

It ends up looking like this:

from switch_case import switch, case         # note the import style

x = 42
switch(x)                                    # note the switch statement
if case(1):                                  # note the case statement
    print(1)
if case(2):
    print(2)
if case():                                   # note the case with no args
    print("Some number besides 1 or 2")

So, my questions are: Is this a worthwhile creation? Do you have any suggestions for making it better?

I put the include file on github, along with extensive examples. (I think the entire include file is about 50 executable lines, but I have 1500 lines of examples and documentation.) Did I over-engineer this thing, and waste a bunch of time, or will someone find this worthwhile?

Edit:

Trying to explain why this is different from other approaches:
1) Multiple paths are possible (executing two or more cases), which is harder in the dictionary method.
2) can do checking for comparisons other than "equals" (such as case(less_than(1000)).
3) More readable than the dictionary method, and possibly if/elif method
4) can track how many True cases there were.
5) can limit how many True cases are permitted. (i.e. execute the first 2 True cases of...)
6) allows for a default case.

Here's a more elaborate example:

from switch_case import switch, case, between

x=12
switch(x, limit=1)                # only execute the FIRST True case
if case(between(10,100)):         # note the "between" case Function
    print ("%d has two digits."%x)
if case(*range(0,100,2)):         # note that this is an if, not an elif!
    print ("%d is even."%x)       # doesn't get executed for 2 digit numbers,
                                  # because limit is 1; previous case was True.
if case():
    print ("Nothing interesting to say about %d"%x)



# Running this program produces this output:

12 has two digits.

Here's an example attempting to show how switch_case can be more clear and concise than conventional if/else:

# conventional if/elif/else:
if (status_code == 2 or status_code == 4 or (11 <= status_code < 20) 
          or status_code==32):
    [block of code]
elif status_code == 25 or status_code == 45:
    [block of code]
if status_code <= 100:
    [block can get executed in addition to above blocks]

# switch_case alternative (assumes import already)
switch(status_code)
if case (2, 4, between(11,20), 32):   # significantly shorter!
    [block of code]
elif case(25, 45):
    [block of code]
if case(le(100)):
    [block can get executed in addition to above blocks]

The big savings is in long if statements where the same switch is repeated over and over. Not sure how frequent of a use-case that is, but there seems to be certain cases where this makes sense.

The example file on github has even more examples.

like image 646
jerfelix Avatar asked Mar 26 '11 07:03

jerfelix


People also ask

Why switch case is not used in Python?

Python doesn't have a switch/case statement because of Unsatisfactory Proposals . Nobody has been able to suggest an implementation that works well with Python's syntax and established coding style.

Does switch case work in Python?

Unlike C++, Java, Ruby, and other programming languages, Python does not provide a switch case statement, but it offers few workarounds to make this statement work. For example, Python allows you to create your code snippets that work like Python Switch case statements in the other programming languages.

Is switch better than if else Python?

Both if-else and switch have their own set of advantages over one another. It is ideal to use if else when checking if a condition is true or false. It is ideal to use a switch instead of using nested if-else statements as it is faster due to the creation of a jump table.


1 Answers

So, my questions are: Is this a worthwhile creation?

No.

Do you have any suggestions for making it better?

Yes. Don't bother. What has it saved? Seriously? You have actually made the code more obscure by removing the variable x from each elif condition.. Also, by replacing the obvious elif with if you have created intentional confusion for all Python programmers who will now think that the cases are independent.

This creates confusion.

The big savings is in long if statements where the same switch is repeated over and over. Not sure how frequent of a use-case that is, but there seems to be certain cases where this makes sense.

No. It's very rare, very contrived and very hard to read. Seeing the actual variable(s) involved is essential. Eliding the variable name makes things intentionally confusing. Now I have to go find the owning switch() function to interpret the case.

When there are two or more variables, this completely collapses.

like image 172
S.Lott Avatar answered Sep 19 '22 02:09

S.Lott