enum_switch: a enum-based switch thing for Python
I am doing a series of videos (spanish only!) about "modern Python", showing the modern replacements for things that are ... dense in their original forms.
So, I showed Poetry as an alternative to writing your setup.py and Click as a way to do things easier than argparse, and Pathlib instead of os.path and then I wanted to show Enums. Which are not so new since they have been there since Python 3.4 but I feel they are not used widely enough.
And then I noticed that they help do a "safer" version of the classical Python version of C's switch / case where you can be sure of not leaving any values unhandled.
So, I wrote a little thing and pushed it to PyPI: https://pypi.org/project/enum-switch/
It's a tiny project, but here's an example of how you use it.
from enum import Enum from enum_switch import Switch class Color(Enum): RED = 1 GREEN = 2 BLUE = 3 class MySwitch(Switch): def RED(self): return "Apple" def GREEN(self): return "Kiwi" def BLUE(self): return "Sky" switch = MySwitch(Color) print(switch(Color.RED)) Apple
If MySwitch was missing one of those "handlers" for the Enum values? That's an exception. If you don't want to define them all? Do a default() there.
I like this solution, but am very interested to know if someone has come up with a better one? Comments are enabled, feel free to tell me :-)