Overriding logical operators?

Robert Brewer fumanchu at amor.org
Sat Aug 21 08:28:20 CEST 2004


Andrew Durdin wrote:
> In Python, you can override the behaviour of most operators for a
> class, by defining __add__, __gt__, and the other special object
> methods.
> 
> I noticed that, although there are special methods for most operators,
> they are conspicuously absent for the logical "or" and "and". I'm
> guessing that the reason for this is that these operators
> short-circuit if their first operand answers the whole question?
> 
> Would it be possible to allow overriding the logical operators, with
> the caveat that overriding it would prevent short-circuiting?

This has come up before--in particular, I think Greg Ewing was taking a
stab at it last. Google is your friend. Anything's possible if you're
willing to write it. ;)

The first barrier is that 'or' and 'and' get compiled down to jump
codes, as opposed to operations:

>>> dis.dis(lambda x: (x + 3) or (x - 5))
  1           0 LOAD_FAST                0 (x)
              3 LOAD_CONST               1 (3)
              6 BINARY_ADD          
              7 JUMP_IF_TRUE             8 (to 18)
             10 POP_TOP             
             11 LOAD_FAST                0 (x)
             14 LOAD_CONST               2 (5)
             17 BINARY_SUBTRACT     
        >>   18 RETURN_VALUE        

...so you'd be hacking a completely different section of the compiler to
enable such overriding.


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org



More information about the Python-list mailing list