Is it ok to type check a boolean argument?

Adal Chiriliuc adal.chiriliuc at gmail.com
Thu Jan 8 00:38:05 CET 2009


On Jan 7, 10:15 pm, Bruno Desthuilliers
<bdesth.quelquech... at free.quelquepart.fr> wrote:
> This being said, I can only concur with other posters here about the
> very poor naming. As far as I'm concerned, I'd either keep the argument
> as a boolean but rename it "ascending" (and use a default True value),
> or keep the 'order' name but then accept 'asc' and 'desc' as values
> ('asc' being the default).

Well, I lied a bit :-p

The actual function is 20 lines long, and does other stuff to. The
"order" argument is not passed as an argument, but as a field on an
input object. Since I generally don't like it when people post
questions and include gazillions of lines of code, I boiled down the
real function to the one posted above, which is the minimum required
to show our dilemma. "_find" also does not exist in the real code.

You are all right, "order" is a bad name choice. "sort_ascending"
would be a much better name for a boolean variable.

I found Paul's idea very interesting, but I prefer to not introduce
new objects which behave like C enums (maybe that would be more
Pythonic?), so I found this variant:

def find(field, sort_ascending):
....order_by = {True: "asc", False: "desc"}
....return _find(field + "+" + order_by[sort_ascending])

But what if we can't solve it as ellegantly, and we need to execute
different code depending on the condition:

def find(field, fast_mode=True):
....if fast_mode:
........do_something(field, 1, DEFAULT_PAGE_SIZE)
....else:
........do_another_thing(field, False, "xml", ignore_error=False)
........and_another_one()

Should we typecheck in this case to ensure that if we pass a string
for "fast_mode" we will raise an exception?



More information about the Python-list mailing list