[Python-ideas] Type hints for functions with side-effects and for functions raising exceptions

Chris Angelico rosuav at gmail.com
Fri Feb 22 17:20:35 EST 2019


On Sat, Feb 23, 2019 at 9:14 AM Kyle Lahnakoski <klahnakoski at mozilla.com> wrote:
> Let me call this pattern the Catch-It-Name-It-Chain-It-Raise-It (CNCR)
> pattern
>
> There are a few reasons for this.
>
> 1. I can add runtime values to the exception so I get a better sense of
> the program state without going to the debugger:  `error("some
> description", {"url": url}, cause=e)`
> 2. I prevent exception leakage; I have no idea the diversity of
> exceptions my code can raise, so I CNCR.
> 3. Every exception is it's own unique type; I can switch on the message
> if I want (I rarely do this, but it happens, see below)
>
> Can Python provide better support for the CNCR pattern? If it is
> lightweight enough, maybe people will use it, and then we can say
> something useful about the (restricted) range of exceptions coming from
> a method:

The CNCR pattern, if used repeatedly, will quickly create a long chain
of exceptions, where each exception represents one function call.
Python already has very good support for seeing the function call
history that led to the exception - it's called a traceback. You even
get the full function locals as part of the exception object... and it
requires no code whatsoever! Simply allowing exceptions to bubble up
will have practically the same benefit.

ChrisA


More information about the Python-ideas mailing list