[Python-ideas] Break the dominance of boolean values in boolean context

Nick Coghlan ncoghlan at gmail.com
Fri Sep 16 03:38:35 CEST 2011

On Fri, Sep 16, 2011 at 10:39 AM, Greg Ewing
<greg.ewing at canterbury.ac.nz> wrote:
> If the objects don't do anything special, the extra
> computation reduces to noticing that a particular type
> slot is NULL at the C level.

abstract.c says "Hi!". The memory layout of type objects means the
dance to handle binary operators correctly is generally a little more
complicated than that. The short circuiting support in PEP 335 will
only make it worse, since there would be two slots to check on each

In this particular case though, the additional problem is that the
interpreter currently treats 'and' and 'or' as flow control
structures, not operators:

# python 3.2
>>> dis.dis("x & y")
  1           0 LOAD_NAME                0 (x)
              3 LOAD_NAME                1 (y)
              6 BINARY_AND
              7 RETURN_VALUE
>>> dis.dis("x and y")
  1           0 LOAD_NAME                0 (x)
              3 JUMP_IF_FALSE_OR_POP     9
              6 LOAD_NAME                1 (y)
        >>    9 RETURN_VALUE

That means making it possible to overload them is actually a fairly
deep change to the expression semantics as far as the compiler is
concerned. The control flow would need to be something like:

  JUMP_IF_LOGICAL_AND <target> (<-- handle shortcircuiting cases)
  LOGICAL_AND (<-- handle binary version, potentially doing stack
twiddling to ditch LH operand if there are no slots to call)
  <target> RETURN_VALUE

That's why my suggestion to consider '&&' and '||' as alternate, lower
precedence, spellings of '&' and '|' wasn't entirely in jest. Their
overloading semantics could be identical to the existing bitwise
operators, but their precedence would be just above that of the
control flow operations.

Having operators that are equivalent aside from subtle details of
precedence would be odd, but it strikes me as being less problematic
overall than messing with the control flow semantics of 'and' and
'or'. Reusing the '&' and '|' typeslots would also mean that existing
libraries like SQLAlchemy that already use '&' and '|' for boolean
logic would just work with the new operators.

C/C++ programmers would get rather confused when they found out that
'&&' and '||' on numeric types still resulted in bitwise operations,


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

More information about the Python-ideas mailing list