On 2020-04-07 10:12 p.m., Soni L. wrote:
the fact that exception handlers aren't reusable and composable is really bothering me so I would like to propose something to make them reusable and composable.
for example, if I have this mess:
def get_property_values(self, prop): try: factory = self.get_supported_properties()[prop] except KeyError as exc: raise PropertyError from exc iterator = factory(self._obj) try: first = next(iterator) except StopIteration: return (x for x in ()) except abdl.exceptions.ValidationError as exc: raise LookupError from exc return itertools.chain([first], iterator)
I get to refactor it into:
def keyerror_handler(exc): raise PropertyError from exc
def other_handler(exc): if isinstance(exc, StopIteration): return (x for x in ()) raise LookupError from exc
def get_property_values(self, prop): try: factory = self.get_supported_properties()[prop] except KeyError with keyerror_handler: pass iterator = factory(self._obj) try: first = next(iterator) except (StopIteration, abdl.exceptions.ValidationError) with other_handler as result: return result return itertools.chain([first], iterator)
and the handlers become reusable!
another idea would be to use semicolons:
def get_property_values(self, prop): try: factory = self.get_supported_properties()[prop] except KeyError with keyerror_handler; iterator = factory(self._obj) try: first = next(iterator) except abdl.exceptions.ValidationError with validation_handler; except StopIteration: return (x for x in ()) return itertools.chain([first], iterator)
but nobody likes semicolons
I sent too soon. here's also something that would be nice: def get_property_values(self, prop): try: factory = self.get_supported_properties()[prop] except KeyError with keyerror_handler; iterator = factory(self._obj) try: first = next(iterator) except abdl.exceptions.ValidationError with validation_handler; except StopIteration with stop_handler as return return itertools.chain([first], iterator) (using "return" as the result target for the handler. doesn't need semicolon, as it can't be ambiguous.)