On Jan 7, 2009, at 12:24 PM, 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?

IMHO you should not.

The pro argument was that if a new programmer comes and passes a
wrongly typed argument, he will get a silent failure.

"Wrongly typed" is a matter of opinion. The following values also evaluate to False when converted to bool:
None
[]
()
""
{}

To me, they're just as false as False is, if you catch my meaning. I would not like to have to convert them to bool to be able to use them when calling your function.

Imagine this scenario --

   order = read_order_from_preferences_xml_file(default_value = None)

   # order is now "ascending" or None

   find(the_field_name, order)


It seems logical to pass a string or None in this case without converting them to bool.

You might feel more comfortable if the parameter was called "is_ordered", which would at least imply that it is a boolean so that someone unfamiliar with the interface would be less tempted to pass something like the last part of an ORDER BY statement, like "last_name, first_name, age DESC".

I can understand your temptation to enforce bool-ness, but you have a very good point about this one function then being different from all of the others that aren't as picky.

HTH
Philip





--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to