Is it ok to type check a boolean argument?

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Thu Jan 8 07:38:19 EST 2009


Adal Chiriliuc a écrit :
> 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.

Then the input object should probably be responsible for validating this 
(IMHO).

(snip)
> 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])

for a simple True/False dispatch, my usual idiom (predating the ternary 
operator) is:

       order_by = ("desc", "asc")[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?

I don't think so. Going that way, you will end up typechecking each and 
any function argument. While there are a couple typechecks here and 
there even in the stdlib and builtins, this doesn't mean it's how Python 
is supposed to be used - Python is a dynamic language, leave with it or 
  choose another one !-)

But anyway, ensuring a program's correctness requires much more than 
static typing. What you want IMHO is:

1/ a solid *user input* validation/conversion framework (FormEncode 
comes to mind)
2/ a sensible set of unittests and integration tests.

Trying to forcefit static typing into Python will only buy you pain and 
frustration (not even talking about the waste of time).



More information about the Python-list mailing list