According to the Cython documentation regarding arithmetic special methods (operator overloads), the way they’re implemented, I can’t rely on self being the object whose special method is being called.
Evidently, this has two consequences:
- I can’t specify a static type in the method declaration. For example, if I have a class
Foowhich can only be multiplied by, say, anint, then I can’t havedef __mul__(self, int op)without seeingTypeErrors (sometimes). - In order to decide what to do, I have to check the types of the operands, presumably using
isinstance()to handle subclasses, which seems farcically expensive in an operator.
Is there any good way to handle this while retaining the convenience of operator syntax? My whole reason for switching my classes to Cython extension types is to improve efficiency, but as they rely heavily on the arithmetic methods, based on the above it seems like I’m actually going to make them worse.
If I understand the docs and my test results correctly, you actually can have a fast
__mul__(self, int op)on aFoo, but you can only use it asFoo() * 4, not4 * Foo(). The latter would require an__rmul__, which is not supported, so it always raisesTypeError.The fact that the second argument is typed
intmeans that Cython does the typecheck for you, so you can be sure that the left argument is reallyself.