Inspired by with-handlers in Racket:
def with_handlers(handlers: Dict[Type[Exception], Callable[[Exception], S]], f: Callable[[], T]) -> Union[S, T]:
try:
return f()
except tuple(handlers.keys()) as err:
return handlers[type(err)](err)
handlers contains all expected exceptions and their corresponding handlers.
And here is a catch function, which also supports else and final clauses:
def catch(
try_clause: Callable[[], T],
except_clauses: Dict[Type[Exception], Callable[[Exception], S]],
else_clause: Optional[Callable[[T], R]] = None,
final_clause: Optional[Callable[[Union[T, S]], None]] = None) -> Union[R, S, T]:
try:
ret = try_clause()
except tuple(except_clauses.keys()) as err:
handled = except_clauses[type(err)](err)
return handled
else:
return ret if else_clause is None else else_clause(ret)
finally:
if final_clause is not None:
try:
final_clause(ret)
except NameError:
final_clause(handled)
In Python, try statements do not introduce their own scope,
but here try_clause is a function, so else_clause needs a parameter to receive information from try_clause.
Similarly, final_clause needs two parameters.
variablethen it won't get assigned, and will already be an empty string when you hit the except block. It may not shorten your code by much, but there's no need to assign it the value it already holds...passto the except, so it's still the same number of lines. It's the pre-try-exceptinitialization that is unecessary.