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

Ben Rudiak-Gould benrudiak at gmail.com
Thu Feb 21 21:34:21 EST 2019


> It's well documented how checked exceptions lead to bad code.

Please cite a paper. I know "everyone knows" that they're bad, but
"everyone knows" a lot of things.

Here's a recentish proposal by Herb Sutter to add a kind of checked
exception to C++:

    http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0709r0.pdf

He talks about some of the same issues I've talked about in this
thread: in particular, that the farther exceptions propagate, the less
likely that they can be handled in a precise way. In practice,
exceptions are either handled early or they are handled generically
(e.g. by printing a traceback).

> Exceptions may be logically thought as of part of the type of a method,

Yes, exceptions designed to be caught and handled by the caller are
essentially alternate return values. Examples are KeyError for mapping
lookups, FileNotFoundError for open(), etc. They are part of the
method's interface whether they are encoded in a type system or not.

> but that requires that the type catches every exception that may be raised from the implementation and either handles it, or translates it to one belonging to the type.

What you're describing is strong static typing. Yes, it is a hassle.
It means you have to do a lot of up-front work proving that your
program will handle *every* case before the implementation will permit
you to run it on *any* case. A lot of programmers don't like that.
They want to write code that works for the cases they care about in
the moment, and think about the other cases "later" (which in practice
often means "after the product has shipped and someone files a bug
report").

> It's a lot of work, it's cumbersome, and it is fragile, as the exception handling may need to change over minor implementation changes.

Yes, it's a lot of work and cumbersome. In exchange for this extra
effort, you get static guarantees that make it easier to reason about
the behavior of the program.

> The strategy of catching only exceptions of interest and letting others pass produces less fragile and easier to test code.

It is less of a hassle to write unchecked code. I don't know if it's
easier to test, but maybe. It isn't less fragile, at least not in the
way I understand "fragile." Fragile code isn't code that is prone to
compile-time type errors when it's changed. Fragile code is code
that's prone to crashes or other broken behavior at runtime when it's
changed, because of hidden constraints that weren't expressible in the
type system. At least, that's what "fragile" means in "fragile base
class problem."


More information about the Python-ideas mailing list