combining several lambda equations

Peter Otten __peter__ at web.de
Fri Feb 18 07:01:00 EST 2005


paddy3118 at netscape.net wrote:

> I actually have a set of lambdas so my use will be more like:

A set of lambdas gains you nothing.

>>> (lambda: a > 0) in set([lambda: a > 0])
False

is probably not what you expected. So you might want to go back to strings
containing expressions. Anyway, here is a way to "and" an arbitrary number
of functions (they all must take the same arguments):

>>> def make_and(*functions):
...     def all_true(*args, **kw):
...             for f in functions:
...                     if not f(*args, **kw):
...                             return False
...             return True
...     return all_true
...
>>> abc = make_and(lambda: a > 0, lambda: b < 0, lambda: c == 0)
>>> a, b, c = 1, -1, 0
>>> abc()
True
>>> c = 1
>>> abc()
False

For a set/list of lambdas/functions, you would call make_and() with a
preceding star:

and_all = make_and(*some_set_of_functions)

> - Gosh, isn't life fun!

I seem to remember that the manual clearly states otherwise :-)

Peter





More information about the Python-list mailing list