PEP 335: Overloadable Boolean Operators - Official Posting

Gerrit gerrit at nl.linux.org
Fri Sep 10 07:16:58 EDT 2004


Hello,

Greg Ewing wrote:
> At the Python level, objects may define the following special methods.
> 
> ===============  =================  ========================
> Unary            Binary, phase 1    Binary, phase 2
> ===============  =================  ========================
> * __not__(self)  * __and1__(self)   * __and2__(self, other)
>                  * __or1__(self)    * __or2__(self, other)
>                                     * __rand2__(self, other)
>                                     * __ror2__(self, other)
> ===============  =================  ========================
> 
> The __not__ method, if defined, implements the 'not' operator.  If it
> is not defined, or it returns NotImplemented, existing semantics are
> used.

I like the idea but I don't like the method names. I don't like numbers
in method names, since they don't intuitively tell the user about what
it does. In my opinion, and1 should be called and, or1 or, rand2 rand
and ror2 ror. The only two left are then and2 and or2. Another
possibility: always have a second argument in and, and default it to
None. It can return NeedOtherOperand or similar if it needs, and ignore
it otherwise. It results in a problem when the second operand is None,
but perhaps that can be circumvented. Something in this direction may be
more elegant than having 3 methods just for and.

def __and__(self, other):
    if self.value % 3 == math.ceil(random.random()):
        return self
    elif other is None: # or SomeSpecialValue
        return NeedOtherOperand
    else:
        return other

Another disadvantage is yet more cluttering of builtins, because
NeedOtherValue would need to be a builtin.

> As a special case, if the first operand defines a phase 2 method but
> no corresponding phase 1 method, the second operand is always
> evaluated and the phase 2 method called.  This allows an object which
> does not want short-circuiting semantics to simply implement the
> relevant phase 2 methods and ignore phase 1.

What happens if an object defines only rand2? Does it depend on the left
operand to be called, or is it always called? E.g. can the right operand
influence short-circuiting (I assume not)?

Excellent PEP, btw.

Gerrit.

-- 
Weather in Twenthe, Netherlands 10/09 11:25:
	20.0°C Few clouds mostly clear wind 3.6 m/s SE (57 m above NAP)
-- 
Experiences with Asperger's Syndrome:
	EN http://topjaklont.student.utwente.nl/english/
	NL http://topjaklont.student.utwente.nl/



More information about the Python-list mailing list