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

2024/9/23 20:47:43

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 stylex = 42
switch(x)                                    # note the switch statement
if case(1):                                  # note the case statementprint(1)
if case(2):print(2)
if case():                                   # note the case with no argsprint("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, betweenx=12
switch(x, limit=1)                # only execute the FIRST True case
if case(between(10,100)):         # note the "between" case Functionprint ("%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.

Answer

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.

https://en.xdnf.cn/q/71746.html

Related Q&A

Replacing the existing MainWindow with a new window with Python, PyQt, Qt Designer

Im new to Python GUI programming Im have trouble making a GUI app. I have a main window with only a button widget on it. What i want to know is how to replace the existing window with a new window when…

Using LaTeX Beamer to display code

Im using the following LaTeX code in a Beamer presentation:\begin{frame}\begin{figure}\centering\tiny\lstset{language=python}\lstinputlisting{code/get_extent.py}\end{figure} \end{frame}Is it possible t…

Python metaclass and the object base class

After reading the excellent SO post, I tried crafting a module level metaclass:def metaclass(future_class_name, future_class_parents, future_class_attrs):print "module.__metaclass__"future_cl…

Is this the equivalent of a copy constructor in Python?

Im reviewing some old python code and came accross this pattern frequently:class Foo(object):def __init__(self, other = None):if other:self.__dict__ = dict(other.__dict__)Is this how a copy constructor…

Fabric error No handlers could be found for logger paramiko.transport

Im not sure why Im getting this error thats terminating my connection. I updated paramiko-1.7.6 from 1.7.5 via easy_install.Im trying to setup Fabric to upload my Django app to my server. The error see…

How to mix unbalanced Datasets to reach a desired distribution per label?

I am running my neural network on ubuntu 16.04, with 1 GPU (GTX 1070) and 4 CPUs.My dataset contains around 35,000 images, but the dataset is not balanced: class 0 has 90%, and class 1,2,3,4 share the …

Is there a way to prevent pandas to_json from adding \?

I am trying to send a pandas dataframe to_json and I am having some issues with the date. I am getting an addtional \ so that my records look like Updated:09\/06\/2016 03:09:44. Is it possible to not…

Convert SQL into json in Python [duplicate]

This question already has answers here:return SQL table as JSON in python(15 answers)Closed 8 years ago.I need to pass an object that I can convert using $.parseJSON. The query looks like this:cursor.e…

Django Middleware - How to edit the HTML of a Django Response object?

Im creating a custom middleware to django edit response object to act as a censor. I would like to find a way to do a kind of search and replace, replacing all instances of some word with one that I c…

Disable or restrict /o/applications (django rest framework, oauth2)

I am currently writing a REST API using Django rest framework, and oauth2 for authentication (using django-oauth-toolkit). Im very happy with both of them, making exactly what I want.However, I have on…