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:
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
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)