C extension objects: possible to obtain __rmul__ functionality?

Greg Ewing (using news.cis.dfn.de) me at privacy.net
Fri Mar 28 01:00:03 CET 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
       # isinstance(y, my_type) must be true
       # I am the right operand

Greg Ewing, Computer Science Dept,
University of Canterbury,	
Christchurch, New Zealand

More information about the Python-list mailing list