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
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/Q33L7JYVJA4LVBZDZUE4SY3K4ZUBO6KI/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to