Alternatives to switch statement from other languages
There is NO switch statement in python as a language design choice. There has been a PEP (PEP-3103) covering the topic that has been rejected.
You can find many list of recipes on how to do your own switch statements in python, and here I'm trying to suggest the most sensible options. Here are a few places to check:
Use a dict of functions
Another straightforward way to go is to create a dictionary of functions:
then you add a default function:
and you use the dictionary's get method to get the function given the value to check and run it. If value does not exists in dictionary, then
default_case is run.
you can also make some syntactic sugar so the switch looks nicer:
Use class introspection
You can use a class to mimic the switch/case structure. The following is using introspection of a class (using the
getattr() function that resolves a string into a bound method on an instance) to resolve the "case" part.
Then that introspecting method is aliased to the
__call__ method to overload the
Then to make it look nicer, we subclass the
SwitchBase class (but it could be done in one class), and there we define all the
case as methods:
so then we can finally use it:
Use what the language offers: the if/else construct.
Well, if you want a
case construct, the most straightforward way to go is to use the good old
it might look redundant, and not always pretty, but that's by far the most efficient way to go, and it does the job:
Using a context manager
Another way, which is very readable and elegant, but far less efficient than a if/else structure, is to build a class such as follows, that will read and store the value to compare with, expose itself within the context as a callable that will return true if it matches the stored value:
then defining the cases is almost a match to the real
case construct (exposed within a function below, to make it easier to show off):
So the execution would be:
- This solution is being offered as the switch module available on pypi.