[Merge] lp:~barry/apport/lp1566975 into lp:~ubuntu-core-dev/ubuntu/xenial/apport/ubuntu

Barry Warsaw barry at canonical.com
Thu Apr 7 13:39:23 UTC 2016


On Apr 07, 2016, at 08:44 AM, Martin Pitt wrote:

>The bug report doesn't contain the actual error message/traceback you got,
>but I suppose it looked something like

Oops, sorry about that!  I should have included the traceback.

>Hmm, a lot of software uses assertions to verify that its input arguments are
>correct, i. e. match the declared API. That's why I'm using assert here. In
>this case the package hook violates the spec, so I suppose an assertion
>exception is as good as any? But if you say that in Python bad input to
>methods should rather raise a ValueError I'm happy to change it.

Generally yes, IMHO best practice is that assertions are there to ensure that
your own logic about a particular state is correct.  Something like, "at this
point x must be 7, otherwise my understanding of how this calculation works is
completely wrong" or "I've checked everything, so y cannot possibly be None,
unless I missed something".

Invalid input, especially if it can come from outside your code, e.g. from a
plugin or external client of your library, should raise ValueError, although
in some cases a TypeError may also be appropriate.  Because Python discourages
type checking for duck typing, TypeError is less common.

One important reason to favor ValueError over assert is that asserts get
no-oped when the .py is compiled with -O:

https://docs.python.org/3/reference/simple_stmts.html#the-assert-statement

Even though it may not happen much in practice, it's entirely possible, so you
wouldn't want this important input validation check to be skipped when the
code is optimized.  Raising AssertionError explicitly would avoid that, but
because of the semantics, I still think ValueError is the better exception to
raise in this case.

-- 
https://code.launchpad.net/~barry/apport/lp1566975/+merge/291144
Your team Ubuntu Core Development Team is subscribed to branch lp:~ubuntu-core-dev/ubuntu/xenial/apport/ubuntu.



More information about the Ubuntu-reviews mailing list