Equivalent code to the bool() built-in function

Chris Angelico rosuav at gmail.com
Tue Apr 19 05:00:19 EDT 2011

On Tue, Apr 19, 2011 at 6:43 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> but I don't see how
> (arbitrary expression) + (another expression) + ... + (last expression)
> can have any guarantees applied. I mean, you can't even guarantee that
> they won't raise an exception. Can you explain what you mean?

What Christian posted isn't something I've often done, but here's
something slightly different that exploits the same
comparisons-return-summable-values concept:

A condition with N subconditions is deemed to be satisfied if a
minimum of M of them are true. This is a general case of the boolean
Or (N = 2, M = 1) and And (N = 2, M = 2), but does not have a direct
equivalent in binary operators. You simply sum the subconditions,
compare against M, and you have your answer.

if (((port<1024) + (!ip.startswith("192.168.")) +
(greylist[ip]>time()) + (++spewcnt>10))>=3) // flag this packet as

Contrived example as I don't recall any specifics right now, but this
will pick up any packets where three or more of the conditions are
met. Useful only in fairly specific situations, but I don't know of
any way to do this with just AND/OR/NOT that would be as clear and

Chris Angelico

More information about the Python-list mailing list