[Python-Dev] Advice on numbers.py implementation of binary mixins. (original) (raw)

Jim Jewett jimjjewett at gmail.com
Sun Jun 15 03:54:36 CEST 2008


Raymond Hettinger wrote:

PEP-3141 outlines an approach to writing binary operators to allow the right operand to override the operation if the left operand inherits the operation from the ABC.

Here is my first approximation at how to write them for the Integral mixins:

class Integral(Rational):

def and(self, other): if isinstance(other, (type(self), int, long)): # XXX return int(self) & int(other)

I think for this mixin, it doesn't matter whether other is an Integral instance; it matter whether it is has a more specific solution.

So instead of checking whether isinstance, check whether its rand method is Integral.rand.

I think you also may want to guard against incomplete right-hand operations, by doing something like replacing the simple

return NotImplemented

with

try:
    val = other.__rand__(self)
    if val is not NotImplemented:
        return val
except (TypeError, AttributeError):
    pass
# Use the generic fallback after all
return int(self) & int(other)


More information about the Python-Dev mailing list