Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Operator overloading

  • Author: DagSverreSeljebotn
  • Status: Idea

What could one want to do with operator overloading in Cython?

The cases I can think of:
  1. Simply declare that an operator is available C/C++ side so that one can "let" an operator on the type through. Declaring the type is important so that coercion can happen Cython-side.
  2. Add a thin layer of syntax candy around C functions that does the operation.
  3. Writing new types in Cython itself that supports operator overloading. I haven't checked whether this is already supported.
  4. Do something more complicated Cython-side. For instance, to support negative indices, bounds checking, slices, variable number of arguments etc., quite complicated argument parsing is needed. This is the NumPy case -- first off, the number of arguments will vary, second off, the expression will contain lookups and divisions which are not cached/optimized by GCC on -O3 and thus optimization must happen Cython-side (see GCC experiment below).
In order to make things clearer, I propose that seperate mechanisms are needed for
  • letting through operators from C into Cython on the one hand (tackles 1), and
  • overriding an operator with a Cython expression on the other hand (tackles 2,3,4)

The former is about declaring the capabilities of the type C-side while the latter will be about declaring what Cython-code should be generated when hitting operators.

Syntax

The former case is not discussed here, see [:enhancements/cpp: the C++ page]. For the latter case, Python-like syntax is proposed:

cdef class Foo:
    cdef Foo __add__(self, Foo other):
        return add_foo(self, other)

add_foo might here be either a declared C function or more Cython code. On this level, any kind of fancy parameters for [] is supported, by writing the obvious Cython code to interpret the argument list (as a Python tuple structure).

Which operators?

The normal set of Python binary operators, getitem, setitem etc.

Also some Cython-specific operators are probably wanted for controlling coercion behaviour etc. (similar to C++ cast operators).

Something went wrong with that request. Please try again.