ezod
ezod

Reputation: 7421

Efficient arithmetic special methods in Cython

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:

  1. I can't specify a static type in the method declaration. For example, if I have a class Foo which can only be multiplied by, say, an int, then I can't have def __mul__(self, int op) without seeing TypeErrors (sometimes).
  2. 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.

Upvotes: 2

Views: 237

Answers (1)

Fred Foo
Fred Foo

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

Related Questions