Re:What Is the Switch-Case Equivalent in Python?
by klyrs on Saturday April 03, 2021 @08:12PM
(#26685888)
I've seen it used in ways that make sense. They were small and well-contained, and definitely didn't involve computing a hash.
For a not-small example, if you want to switch on an ascii character in a parser, you can make a 256-element list to implement your jump table, and index into it with ord.
If you're performance-minded enough for this to make a lick of sense, you'll take care to only build the jump table once.
And yeah, chained if/else is cleaner because it's the only tool that the language provides. The GP was asking for alternatives. They exist, but you'll hate them.
Granted, you can speed the 256-long if/elif mess up with a binary if/else tree 8 levels deep. But it probably won't beat the jump table.
If you truly find this upsetting, know that it's a practice that results from the language not supporting a switch statement.
For a not-small example, if you want to switch on an ascii character in a parser, you can make a 256-element list to implement your jump table, and index into it with ord.
If you're performance-minded enough for this to make a lick of sense, you'll take care to only build the jump table once.
And yeah, chained if/else is cleaner because it's the only tool that the language provides. The GP was asking for alternatives. They exist, but you'll hate them.
Granted, you can speed the 256-long if/elif mess up with a binary if/else tree 8 levels deep. But it probably won't beat the jump table.
If you truly find this upsetting, know that it's a practice that results from the language not supporting a switch statement.