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

Matthew Fitzgibbons elessar at nienna.org
Fri Aug 1 08:49:36 EDT 2008


Carl Banks wrote:
> On Jul 31, 11:44 pm, Carl Banks <pavlovevide... at gmail.com> 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.

> 
> The function f could use methods appropriate for ints when x is an
> int, and for lists when x is an int.
> 
> I did downplay this, because frankly, not many programmers use
> functional methods this extensively.  But one should also note that
> you could pass in the test as well:
> 
> def apply_if_condition(func,cond,x):
>     if cond(x):
>         func(x)
> 
> Thus this usage of "if x" arguably could be considered "replaceable
> with a simple explicit test".  But in the interests of harmony I
> didn't push the point, and it really would have been stretching the
> spirit of what I was trying to prove.
> 
> 
> Carl Banks
> --
> http://mail.python.org/mailman/listinfo/python-list
> 

Are you using cond to (a) determine is x is a suitable type to pass to 
func, or (b) whether or not to call func, based on some other 
characteristics of x?

If (a), I think using a condition is this way is a little goofy. Why not 
just allow func to decide is x is an acceptable argument?

(b) is not really what we've been discussing, so I assume not. I would 
seriously consider refactoring cond outside the function anyway.

-Matt



More information about the Python-list mailing list