How much sanity checking is required for function inputs?

Michael Selik michael.selik at gmail.com
Sun Apr 17 18:18:47 EDT 2016


On Sun, Apr 17, 2016, 4:35 PM Christopher Reimer <
christopher_reimer at icloud.com> wrote:

> Greetings,
>
> I'm currently building a chess engine to learn the finer details of
> Python. When I learned all flavors of Java in community college a decade
> ago, we had to sanity check the hell out of the input values for every
> function and wrote a lot of redundant code in addition to the
> getters/setters code.
>
> Here's the input sanity checking I got for a generator function to
> return a set of chess pieces for a specified color and position.
>
>
> def generate_set(color, positions):
>
>      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))
>
>      if len(positions) != 16:
>          raise Exception("Require 16 positions for input value, got {}
> instead.".format(len(positions)))
>
>
> The two sanity checks are fairly straight forward. Color input has to
> match the color constant strings. Positions input has to have 16 items.
>
> I *could* sanity check the positions input to determine if it had a list
> of 16 valid coordinates. The reason I don't is because the code that
> calls this function builds the coordinates from constants with valid
> coordinates. However, if I was doing this in my Java classes, one of my
> instructors rap me on the knuckles for not sanity checking to nth degree.
>
> How much sanity checking is too much in Python?
>

I'd rather turn the question around: how much sanity checking is necessary
or useful? You'll find the answer is "surprisingly little" compared to your
experience in Java. For example, you don't need to explicitly check whether
the color is present in your dictionary, because it'll give you a KeyError
if you look up a bad key.

Why does the len of positions need to be 16?

>



More information about the Python-list mailing list