On 10Apr2019 23:09, Stefano Borini <stefano.bor...@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
example:
- 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': ...
else:
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.
Cheers,
Cameron Simpson <c...@cskk.id.au>
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/