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

Kyle Lahnakoski klahnakoski at mozilla.com
Mon Feb 25 13:00:32 EST 2019


On 2019-02-22 17:20, Chris Angelico wrote:
> On Sat, Feb 23, 2019 at 9:14 AM Kyle Lahnakoski <klahnakoski at mozilla.com> wrote:
>> 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.

I like your point that the exception chain is long, and similar to the
stack: I do find that in practice. This may indicate there is an
optimization in how CNCR can be handled:  Maybe instantiation of CNCR
exceptions can be deferred to the point where an exception handler
actually does something beyond CNCR, if ever.

I also agree, with a debugger at hand, we can inspect the stack trace.
We can also write code that reflects on the method names in the stack
trace to figure out how to handle an exception. But, I am concerned that
stack trace inspection is brittle because methods can be renamed and
refactored.  Also, the CNCR pattern is not 1-1 with methods, there can
be more than one type of CNCR exception emitted from a method.  Methods
could be split, so each only throws one type of exception; and then the
stack trace would suffice; but that brings us back to brittle: A split
method may be accidentally merged for clarity at a later time.

We should also consider what happens in the case that an exception chain
is not handled: It may be printed to the log: We can not reasonably
print all the locals; there are many, some do not serialize, and some
are sensitive.  CNCR is being explicit about what locals(), if any, are
important.





More information about the Python-ideas mailing list