C extension objects: possible to obtain __rmul__ functionality?

Greg Ewing (using news.cis.dfn.de) me at privacy.net
Thu Mar 27 19:00:03 EST 2003


David Abrahams wrote:
> "Bernt Ribbum" <bernt at tordivel.no> writes:
> 
>>I find no way to make the object appear on the right side (PythonObject *
>>CObject), except by overloading the __mul__ function in a Python class (of
>>which PythonObject would be an instance in the example above). I would love
>>to have this handled by a __rmul__ equivalent in my C class.

C objects use the same type slot for both __mul__ and __rmul__.
If the first operand raises NotImplementedError, the __mul__
slot of the second operand is called, with the operands in the
*same* order.

This means that, from the second operand's point of view, the
second operand of its __mul__ method is "self"! This is how
the object can tell whether it's the first or second operand.

So, your __mul__ method needs to do the C equivalent of

   def __mul__(x, y):
     if isinstance(x, my_type):
       # I am the left operand
     else:
       # isinstance(y, my_type) must be true
       # I am the right operand

-- 
Greg Ewing, Computer Science Dept,
University of Canterbury,	
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg





More information about the Python-list mailing list