Is it ok to type check a boolean argument?

James Stroud jstroud at mbi.ucla.edu
Wed Jan 7 19:21:52 EST 2009


Adal Chiriliuc wrote:
> 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?

None of the above. You have put unnecessary constraints on find by 
requiring a certain data type.

def find(field, order_by='desc'):
   return _find(field + "+" + order_by)

Here we are deferring error checking to the _find function. Otherwise:

def find(field, order_by='desc'):
   if order_by not in ['asc', 'desc']:
     raise ValueError, 'Bad order_by parameter.'
   else:
     return _find(field + "+" + order_by)

Now you have achieved the exact same affect without any sort of explicit 
type checking. Moreover, you have eliminated an "if" statement. Also, 
you leave room for exotic orderings should you ever want them.

James



More information about the Python-list mailing list