A manner of replicating the functionality of switch and case in other languages using variable type arguments
to Python's except keyword.
Python's except keyword takes as an argument either a type or tuple of types specifying what exceptions
to capture (you can also bind the exception object to a variable, but we don't care about that right now.) it functions
like so:
try:
some_potentially_erroring_function()
except (Error1, Error2):
handle_err1_err2()
except Error3:
handle_err3()This all seems very standard, until you realize that it takes types and tuples of types as an argument -- meaning that
these can be dynamically produced at runtime. I could assign t = (Error1, Error2) and except t: in the preceding code
snippet, and everything would function identically. Having found a small amount of dynamicism where I did not expect it, I
felt compelled to create the most awful thing possible.
After importing the file, create a Switch object by calling it with predicates (callable objects returning booleans) which
are then numbered (starting at 1, because they aren't members of an array -- they're the first case, second case, etc). Call
its run method, passing in whatever arguments your predicates need, then for each case you wish to implement handling for,
use switch.on_case -- use one argument to specify a singular case, two to specify an (inclusive) range of cases. Be sure
to finish up with an except switch.end(): pass.
- If you forget about a case, and forget to finish with an
except switch.end(): pass, you will get a very interesting "InternalCaseHandlingException" crash. on_case('else')only triggers when no other cases specified in the switch object trigger, rather than the cases listed in the switch statement. For this reason, I recommend not reusing switch objects.You could probably make a ruby-like case using similar methodology, or even just deriving off of this code.- You can, and I just did (see the file
03-ruby-case.py).
- You can, and I just did (see the file
- If you really want case exceptions to be 0-indexed or use exclusive ranges, all the logic for that is all in
on_case. - Don't use this.