[Python-ideas] Exception for developer errors?

Cameron Simpson cs at cskk.id.au
Wed Apr 10 21:06:32 EDT 2019

On 10Apr2019 23:09, Stefano Borini <stefano.borini at gmail.com> wrote:
>I occasionally found situations where I want to raise an exception for
>errors that can only arise because the developer made a mistake, for
>- an abstract method is supposed to be reimplemented and its execution
>is supposed to leave some internal constraints of an object unchanged,
>but these are instead violated.

As mentioned, AssertionErrors are good for this.

I also use the icontract PyPI library, which provides decorators for 
annotating functions with preconditions and postconditions, and which 
are disabled in the same circumstances where assertions are disabled.

It produces nice exception messages, too, aiding debugging.

Also, it inspects the function definition, and so your preconditions use 
the same parameter names as in the function header.

>- an impossible "else" condition after an if/elif, where the else
>cannot simply happen unless someone really screwed up the internal
>state of the object.

That I tend to use RuntimeError for. I accept that my criteria for this 
difference are nebulous.

I think in my mind:

    from icontract import require

    @require(lambda s: s in ('a', 'b', 'c'))
    def f(s, z):
      if s == 'a': ...
      elif s == 'b': ...
        raise RuntimeError("valid input s=%r, but unhandled!" % s)

The @require is an assertion that the _caller_ used us correctly. The 
RuntimeError means that _I_, the function implementor, have screwed up 
right here instead of in the larger programme.

Cameron Simpson <cs at cskk.id.au>

More information about the Python-ideas mailing list