Overloading and? was <RE: Should I prefer an external database>

Steven Taschuk staschuk at telusplanet.net
Tue Apr 22 16:41:58 EDT 2003


Quoth Andrew Dalke:
> Bjorn Pettersen:
  [...]
> > Does anyone know the reason for not allowing an overload of the and
> > operator?
> 
> The 'and' and 'or' operators work on the boolean-ness of the objects,
> and apply short-circuit behaviour.  This is different than other binary
> operators, which don't short-circuit.
  [...]
> There's no way to implement that behaviour in Python, so
> it cannot be overridden.  Eg, suppose there is an "__and__".
> You might think it could look like
> 
>   def __and__(self, other):
>       if bool(self): return self
>       if bool(other): return other
>       return False

__and__ could be passed other as a callable which computes and
returns the second operand.  Then the standard __and__ could be
    def __and__(self, other):
        if bool(self):
            return self
        return other()

(Must return the second object when it is false, thus:
    >>> 1 and []
    []
rather than False.)

-- 
Steven Taschuk                             staschuk at telusplanet.net
"I may be wrong but I'm positive."  -- _Friday_, Robert A. Heinlein





More information about the Python-list mailing list