News for hackers. Stuff that matters.
Re:What Is the Switch-Case Equivalent in Python? by klyrs on Saturday April 03, 2021 @06:44PM (#26685402)
There's one that's even closer to c-like switches: a list/tuple of functions or values, indexed by a small int. If you're feeling extremely cheeky, it can even handle negative cases. You'll have to implement fallthrough yourself, though.
Re:What Is the Switch-Case Equivalent in Python? by rualca on Saturday April 03, 2021 @07:49PM (#26685780)
> There's one that's even closer to c-like switches: a list/tuple of functions or values, indexed by a small int.

That sounds like a desperate plea to get stuck with a bug-riddled unmaintainable mess of a module.

If all you want to do is pick one of a finite set of possible code paths, it is never a good idea to generate a hash to pick from a map/array.

Even chained if/else if statements are cleaner than that mess.

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.