builtin functions for and and or?

John Machin sjmachin at lexicon.net
Sun Feb 13 17:18:04 EST 2005


Michael Hartl wrote:
> I warmly recommend downloading Peter Norvig's Python utilities file
> (http://aima.cs.berkeley.edu/python/utils.py) and putting it on your
> Python path.  (E.g., in bash, put a line like
>
> export PYTHONPATH="/path/to/utilities_directory"
>
> in your .bashrc file.)  The utils.py file defines many useful
> functions, including the ones you want:
>
> # def every(predicate, seq):
> #     """True if every element of seq satisfies predicate.
> #     Ex: every(callable, [min, max]) ==> 1; every(callable, [min,
3])
> ==> 0
> #     """
> #     for x in seq:
> #         if not predicate(x): return False
> #     return True
> #
> # def some(predicate, seq):
> #     """If some element x of seq satisfies predicate(x), return
> predicate(x).
> #     Ex: some(callable, [min, 3]) ==> 1; some(callable, [2, 3]) ==>
0
> #     """
> #     for x in seq:
> #         px = predicate(x)
> #         if px: return px
> #     return False
>

What an interesting mixed API design. The every() function returns True
or False. However the "some" function returns the FIRST fat result if
it's true in the non-boolean sense, otherwise False.

Looks like there could theoretically be scope for two pairs of
functions, one returning strictly True/False, and the other pair
emulating chains of Python 'and's and 'or's.

I.e.
False or 0 or [] evaluates to []
0 or 5 or 6 evaluates to 5
42 and None and True evaluates to None
4 and 5 and 6 evaluates to 6

All very nice, but useful? Dubious. PEPpable? Nah, two thumbs down.

Diez's advice to the OP is sound: if it bothers you that much, mine the
net for, or write, routines that do exactly what you want, and put them
in your own utilities module.




More information about the Python-list mailing list