Boolean tests [was Re: Attack a sacred Python Cow]

Carl Banks pavlovevidence at
Fri Aug 1 19:54:53 CEST 2008

On Aug 1, 8:49 am, Matthew Fitzgibbons <eles... at> wrote:
> Carl Banks wrote:
> > On Jul 31, 11:44 pm, Carl Banks <pavlovevide... at> wrote:
> > [snip excellent explanation of why it's hard to for "if x" to be
> > extensively polymorphic]
> > By the way, one thing I forgot to mention is Matt Fitzgibbons' filter
> > example.
> > As I said, it's hard to write code that works for both numeric and
> > container types because they share so few methods.  However, sometimes
> > you don't know ahead of time what methods are used!  When you're doing
> > functional programming you might pass in a method that calls the
> > appropriate method, like so:
> > def apply_if_true(func,x):
> >     if x:
> >         func(x)
> I find myself doing things like this surprisingly often. All you've done
> is move the decision as to what function is applied to x elsewhere. Like
> a factory, for example. I could see using something like this where func
> prepares object x to be inserted into a database, and you want to make
> sure x is meaningful first.
> def add_to_db(prep_func, x):
>      if x:
>          entry = prep_func(x)
>          add_to_db(entry)
> 'if x' strikes me as better for this case because you might want to
> accept a non-empty list (or some other objects) but reject non-empty
> lists. 'if x is None' would not work. It still may be susceptible to the
> empty iterator problem, depending on what prep_func does.

What if what you consider to be "meaningful" doesn't happen to
coincide with what Python considers to be "something".  For instance,
what if being non-negative is what makes an integer meaningful?  You
can't use "if x" for that.  What if any list, including an empty one,
is meaningful, but you want to indicate the possibility of an
unmeaningful value by passing None?  You can't use "if x" for that.

So, you might address this issue by doing something like this:

def add_to_db(prep_func, is_meaningful, x):
     if is_meaningful(x):
         entry = prep_func(x)

But if you do that, what has the polymorphism of "if x" gained you?

The thing it gained for you before is not having to pass in a
condition: whether x was a sequence, number, or whatever, the same
condition could be used, and thus you avoided considerable
complexity.  But if you have to perform tests for which the implicit
boolean doesn't work, that complexity has to be added to the code

That matters in the context of this discussion because it limits the
usefulness of the polymorphism of "if x" for this functional idiom:
"if x" only helps you if you have no need for tests that it can't


Carl Banks

More information about the Python-list mailing list