Overriding logical operators?

Oliver Fromme olli at haluter.fromme.com
Mon Aug 23 12:24:31 EDT 2004


Andrew Durdin <adurdin at gmail.com> wrote:
 > On Sat, 21 Aug 2004 16:06:08 -0500, Chris Siebenmann
 > <cks at cquest.utoronto.ca> wrote:
 > >  Conceptually, 'and' and 'or' (and 'not') don't operate on objects:
 > > they operate on truth values (generally derived from objects).
 > 
 > But in Python, a "truth value" is an object: a bool object.

Actually, that's not the whole truth.  ;-)

The logical operators on Python operate on arbitrary objects
interpreted in a boolean context, but they're not restricted
to bool objects.  Furthermore, the "or" and "and" operators
return the operand which has been evaluated last, which can
be an arbitrary object (not neccessarily a bool object).  Of
course, the "not" operator always returns a real bool object
(either True or False).

For example, the expression ``"ugh" or 15'' evaluates to the
string "ugh", and ``0 or []'' evaluates to an empty list.

So, the logical operators have more built-in magic than just
short-circuit evaluation.  The details are in the Language
Reference.  Providing a clean facility to override them in
Python would be very difficult, I guess.

I suggest you simply define your own functions to do what
you need to do, instead of overriding "or" and "and".  If
you only need to work with boolean values, you could derive
your own bool class and override the "+" and "*" operators,
of course.

Best regards
   Oliver

-- 
Oliver Fromme, Konrad-Celtis-Str. 72, 81369 Munich, Germany

``All that we see or seem is just a dream within a dream.''
(E. A. Poe)



More information about the Python-list mailing list