[Python-ideas] Raise exception if (not) true
spir
denis.spir at gmail.com
Fri Feb 21 03:23:21 CET 2014
On 02/20/2014 10:28 PM, Steven D'Aprano wrote:
> On Thu, Feb 20, 2014 at 09:44:57PM +0100, spir wrote:
>
>> >But I would like to be able to add an error type to assertions (in addition
>> >to the optional message). This is particularly useful for people (like me)
>> >who systematically check func inputs (for client debugging comfort), using
>> >assert's.
> Then your code is systematically broken, and badly so.
Why do you speak _that_ negatively? (or should I say: _that_ violently?) And
this, maybe not _that_ logically? Do you own the (copy)rights on proper usage of
assert's?
> All anyone needs
> to do to disable your checking is pass -O to the Python interpreter.
>
> assert is not a short-cut for lazy programmers to avoid having to write
> an explicit "if cond: raise SomethingAppropriate(message)". Assertions
> have specific uses. You should read this post I made last November:
>
> https://mail.python.org/pipermail/python-list/2013-November/660401.html
I think you are wrong, at least in this very case. Assert's for me are a
debugging tool (or maybe more generally a tool for improving reliability). Such
checks help finding errors and correcting them (thank to hopefully clear error
messages), with a higher chance these corrections happen before "too late",
meaning before users pay for our bugs. What else is the proper usage of assertions?
If not checked on function input, either with assert's or an if-raise
combination, execution will break anyway, just later (later in time, and
slightly further in code), because some input variable's value or type is wrong.
Assert's placed that way are not strictly necessary (it's like duck typing: you
don't need to check), instead they're a helpful tool for all users of your
"service".
def average (numbers):
n = len(numbers)
assert n != 0, "Cannot compute average of 'zero number'.", ValueError
return sum(numbers) / n
On the proposal: having a correct error type instead of "AssertionError" just
helps a bit making the error report clearer for developpers.
I note in your post that, according to you, "assertions should be used for"
(among other cases):
"* checking contracts (e.g. pre-conditions and post-conditions);"
This is precisely what I do (pre-conditions).
If you don't use assert's for checking assertions which are logical truths if
the code is correct, then what for?
[Side-note: I do not use here assertions for exception handling (properly
speaking) at all; instead for catching errors (properly speaking). It's just
that, in python and a long list of other languages, there is a complete
confusion between exceptions (which belong to the app's logic, but need to be
processed specially) and errors (which don't, and are our fault and our
problem). Is this topic clear?]
d
More information about the Python-ideas
mailing list