Can you dynamically combine multiple conditional functions into one in Python?

Posted by erich on Stack Overflow See other posts from Stack Overflow or by erich
Published on 2010-06-09T22:14:28Z Indexed on 2010/06/09 22:32 UTC
Read the original article Hit count: 207

I'm curious if it's possible to take several conditional functions and create one function that checks them all (e.g. the way a generator takes a procedure for iterating through a series and creates an iterator).

The basic usage case would be when you have a large number of conditional parameters (e.g. "max_a", "min_a", "max_b", "min_b", etc.), many of which could be blank. They would all be passed to this "function creating" function, which would then return one function that checked them all. Below is an example of a naive way of doing what I'm asking:

def combining_function(max_a, min_a, max_b, min_b, ...):
    f_array = []
    if max_a is not None:
        f_array.append( lambda x: x.a < max_a )
    if min_a is not None:
        f_array.append( lambda x: x.a > min_a )
    ...

    return lambda x: all( [ f(x) for f in f_array ] )

What I'm wondering is what is the most efficient to achieve what's being done above? It seems like executing a function call for every function in f_array would create a decent amount of overhead, but perhaps I'm engaging in premature/unnecessary optimization. Regardless, I'd be interested to see if anyone else has come across usage cases like this and how they proceeded.

Also, if this isn't possible in Python, is it possible in other (perhaps more functional) languages?

© Stack Overflow or respective owner

Related posts about python

Related posts about functional-programming