How much sanity checking is required for function inputs?

Stephen Hansen me at ixokai.io
Wed Apr 20 01:51:15 EDT 2016


On Sun, Apr 17, 2016, at 12:34 PM, Christopher Reimer wrote:
>      if color not in [VARS['COLOR_BLACK'], VARS['COLOR_WHITE']]:
>          raise Exception("Require \'{}\' or \'{}\' for input value, got 
> \'{}\' instead.".format(VARS['COLOR_BLACK'], VARS['COLOR_WHITE'], color))

Do you think it likely you'll receive a 'color' value not in the list of
black and white? Are you accepting colors from users? If you are, I'd
sanity check *at user input*. Users are crazy, sanitize and check the
heck out of their stuff.

Your code, though? Your time and effort is better spent putting in a
docstring documenting what's valid in color, and if some other coder
puts in red, why, they'll get a KeyError, and it'll point to precisely
what line is wrong, and be able to figure it out.

Unit tests are where you try feeding invalid data into functions and see
how they react-- and the correct reaction to bad data is usually
exceptions. In this case, a KeyError thrown by [VARS['COLOR_BLACK'],
VARS['COLOR_WHITE']][color] is more descriptive then your verbose
Exception.

(What's with the VARS business? Something smells bad there. You're doing
something weird there)

> How much sanity checking is too much in Python?

IMHO, you've got too much.

But that's a fuzzy question, there's no solid and clear answer. Did you
see Ethan's response? I largely agree with his trinity:

On Sun, Apr 17, 2016, at 10:26 PM, Ethan Furman wrote:
> I sanity check for three reasons:
> 
> 1) raise a nicer error message
> 
> 2) keep the point of failure close to the error
> 
> 3) the consequences of bad data are Bad Bad Things (tm)

With a 4)th that exceptions aren't for users, only programmers. But
ultimately, I'd rather a user see an exception if something weird goes
wrong because they can send it to me and I can diagnose it and push an
update. So I also:

4) Attempt to make sure all user errors result in user error messages,
not exceptions.

Note, 1) doesn't mean I always raise a nicer message, it means if
"KeyError" is ambiguious or odd, I raise a better and more informative
one. But you're getting nothing swapping out KeyError for
Exception(lotsofwords). 

I use 1) more to be less 'nicer' and more, er, 'more specific'. Since I
don't like exceptions to rise to the user level where niceness is
needed.

--Stephen
m e @ i x o k a i . i o



More information about the Python-list mailing list