Is it ok to type check a boolean argument?

Adal Chiriliuc adal.chiriliuc at gmail.com
Wed Jan 7 12:24:00 EST 2009


Hello,

Me and my colleagues are having an discussion about the best way to
code a function (more Pythonic).

Here is the offending function:

def find(field, order):
....if not isinstance(order, bool):
........raise ValueError("order must be a bool")
....order_by = "asc" if order else "desc"
....return _find(field + "+" + order_by)

We are not sure what's the best practice here. Should we or should we
not check the type of the "order" variable, which should be a bool?

In one of our unit-tests we passed the "invalid_order" string as the
order argument value. No exception was raised, since the string was
evaluated as being True.

We know about "Don't look before we jump", but we are not sure how it
applies in this case, since we don't get any exception when passing an
invalid type argument.

This function is not visible to our clients, only internally in our
project. It's part of the public interface of a sub-system, so we are
not sure either if the fact that it returns an invalid result for a
badly type argument it's an API specification break or not.

The pro argument was that if a new programmer comes and passes a
wrongly typed argument, he will get a silent failure.
The cons argument was that there are many functions which could
silently fail in this mode, especially those having bool arguments.

Should we in general check when doing unit-testing that the methods
behave correctly when passed arguments of the wrong type? What do you
do in your projects?



More information about the Python-list mailing list