4

The following code defines a simple Cython function (using Ipython magic, for convenience).

%load_ext cython
%%cython
def f(float x, float y=2):
    return x+y

Then, calling help(f) gives this message:

Help on built-in function f in module _cython_magic_e37eeabbc63d5167217465ba978239fc:

f(...)

Note that the arguments of f are not shown. Also, the tab-completion does not work either for the argument names in ipython (e.g. typing f(x then tab).

If I define this function without using Cython:

def g(x, y=2):
    return x+y

Calling help(g) gives this and the tab-completion works as expected:

Help on function g in module __main__:

g(x, y=2)

Is there a way to get this behavior with the Cython function? I tried with def, cdef, cpdef, with and without ipython magic, with no success.

Tom Cornebize
  • 1,362
  • 15
  • 33

2 Answers2

5

Disagree with the agreed answer.

While enabling binding does have the side-effect of documentation strings showing up in code, it also binds all other Python class attributes to Cython extension classes which makes for lower performance, more memory used for each extension object and so on.

The correct flag to enable docstrings only without side effects is embedsignature=True.

It can either be used as decorator - @cython.embedsignature(True) on top of all functions, or part of cython directives in setup.py Extension to apply to all Cython functions - {'embedsignature': True}

From docs:

embedsignature (True / False)

If set to True, Cython will embed a textual copy of the call signature in the docstring of all Python visible functions and classes. Tools like IPython and epydoc can thus display the signature, which cannot otherwise be retrieved after compilation. Default is False.

Community
  • 1
  • 1
danny
  • 5,140
  • 1
  • 19
  • 31
  • Well, this is not exactly what I wanted. If I use this, I still get a function with an empty signature `f(...)` (although the correct signature can be found below in the docstring). – Tom Cornebize May 24 '18 at 12:30
  • Oh you mean via `help(func)`. `embedsignature` is only for docstrings. – danny May 24 '18 at 13:38
2
import cython

@cython.binding(True)
def f(float x, float y=2):
    # ...

now help(f) gives

Help on cython_function_or_method in module cy_exc:

f(x, y=2.0)

The documentation says

When enabled, functions will bind to an instance when looked up as a class attribute (hence the name) and will emulate the attributes of Python functions, including introspections like argument names and annotations. Default is False.

You can enable the compilation option in other ways (for example, if you want it enabled everywhere).

You might also want to look at this related question

DavidW
  • 29,336
  • 6
  • 55
  • 86