[Python-ideas] PEP 355 (overloading boolean operations) and chained comparisons

Nick Coghlan ncoghlan at gmail.com
Thu Oct 13 02:39:45 CEST 2011

I had a chance to speak to Travis Oliphant (NumPy core dev) at
PyCodeConf and asked him his opinion of PEP 355. His answer was that
he didn't really care about overloading boolean operations in general
(the bitwise operation overloads with the appropriate objects in the
arrays were adequate for most purposes), but the fact that chained
comparisons don't work for NumPy arrays was genuinely annoying.

That is, if you have a NumPy array, you cannot write:

x = A < B < C

Since, under the covers, that translates to:

x = A < B and B < C

and the result of the first operation will be an array and hence
always true, so 'x' receives the value 'True' rather than an array
with the broadcast chained comparison.

Instead, you have to write out the chained comparison explicitly,
including the repetition of the middle expression and the extra
parentheses to avoid the precedence problems with the bitwise

x = (A < B) & (B < C)

PEP 355 would allow NumPy to fix that by overriding the logical 'and'
operation that is implicit in chained comparisons to force evaluation
of the RHS and return the rich result.


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list