Reputation: 7421
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:
Foo
which can only be multiplied by, say, an int
, then I can't have def __mul__(self, int op)
without seeing TypeError
s (sometimes).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.
Upvotes: 2
Views: 237
Reputation: 363787
If I understand the docs and my test results correctly, you actually can have a fast __mul__(self, int op)
on a Foo
, but you can only use it as Foo() * 4
, not 4 * Foo()
. The latter would require an __rmul__
, which is not supported, so it always raises TypeError
.
The fact that the second argument is typed int
means that Cython does the typecheck for you, so you can be sure that the left argument is really self
.
Upvotes: 2