'and' is not exactly an 'operator' (was Re: numpy.where() and multiple comparisons)

Terry Reedy tjreedy at udel.edu
Sat Jan 18 19:12:35 EST 2014


On 1/18/2014 3:50 AM, Peter Otten wrote:

> Unlike `&` `and` cannot be overridden (*),

> (*) I assume overriding would collide with short-cutting of boolean
> expressions.

Yes. 'and' could be called a 'control-flow operator', but in Python it 
is not a functional operator.

A functional binary operator expression like 'a + b' abbreviates a 
function call, without using (). In this case, it could be written 
'operator.add(a,b)'. This function, or it internal equivalent, calls 
either a.__add__(b) or b.__radd__(a) or both. It is the overloading of 
the special methods that overrides the operator.

The control flow expression 'a and b' cannot abbreviate a function call 
because Python calls always evaluate all arguments first. It is 
equivalent* to the conditional (control flow) *expression* (also not a 
function operator) 'a if not a else b'. Evaluation of either expression 
calls bool(a) and hence a.__bool__ or a.__len__.

'a or b' is equivalent* to 'a if a else b'

* 'a (and/or) b' evaluates 'a' once, whereas 'a if (not/)a else b' 
evaluates 'a' twice. This is not equivalent when there are side-effects. 
Here is an example where this matters.
  input('enter a non-0 number :') or 1

-- 
Terry Jan Reedy




More information about the Python-list mailing list