Question

I'm suprised not to find the boolean (not bitwise) and operator in the operator module:

http://docs.python.org/2/library/operator.html

Why is that so? Is there a workaround?

Was it helpful?

Solution

The Python and and or operators evaluate their expressions lazily, allowing you to use expressions like:

function_object and function_object(some, arguments)
some_value or produce_new_value(expensive, call)

safely.

This disqualifies them for a operator treatment, because you'd have to evaluate the expressions before passing them to the function.

In the above examples that means the and expression cannot be expressed using a operator function; if function_object is false-y it is probably not callable either, and if some_value is true-thy, you don't want to invoke the expensive function call.

It's easy enough to create your own functions if lazy evaluation is not required:

def and_(op1, op2):
    return op1 and op2

def or_(op1, op2):
    return op1 or op2

OTHER TIPS

You can write your own:

logical_and = lambda a, b: a and b
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top