4 ms·
In practice I never try to replicate switch/case in Python but prefer what the author lists as "Dictionary" method. Namely matching an item in a dictionary bas
by INTPenis 6y ago
In practice I never try to replicate switch/case in Python but prefer what the author lists as "Dictionary" method.
Namely matching an item in a dictionary based on either key or perhaps more advanced matching a value inside the dict. Maybe even using re to match it.
Either way, I find using a dictionary is the most Pythonic and clean way to do it. Defining the actions first, how to match them and anything else they might need.
- sidpatil 6y agoI believe this is more generally known as table-driven methods, and I also enjoy using them. They feel more ergonomic than conditional statements, and they're also more flexible—you can dynamically modify the conditions and actions by modifying the data structure which contains them.