Python C extension: method signatures for documentation?

前端 未结 2 1555
不知归路
不知归路 2020-12-10 12:14

I am writing C extensions, and I\'d like to make the signature of my methods visible for introspection.

static PyObject* foo(PyObject *self, PyObject *args)          


        
2条回答
  •  攒了一身酷
    2020-12-10 12:37

    It has been 7 years but you can include the signature for C-extension function and classes.

    Python itself uses the Argument Clinic to dynamically generate signatures. Then some mechanics create a __text_signature__ and this can be introspected (for example with help). @MartijnPieters explained this process quite well in this answer.

    You may actually get the argument clinic from python and do it in a dynamic fashion but I prefer the manual way: Adding the signature to the docstring:

    In your case:

    PyDoc_STRVAR(
        foo_doc,
        "foo(timeout, flags=None, /)\n"
        "--\n"
        "\n"
        "Great example function\n"
        "Arguments: (timeout, flags=None)\n"
        "Doc blahblah doc doc doc.");
    

    I made heavy use of this in my package: iteration_utilities/src. So to demonstrate that it works I use one of the C-extension functions exposed by this package:

    >>> from iteration_utilities import minmax
    >>> help(minmax)
    Help on built-in function minmax in module iteration_utilities._cfuncs:
    
    minmax(iterable, /, key, default)
        Computes the minimum and maximum values in one-pass using only
        ``1.5*len(iterable)`` comparisons. Recipe based on the snippet
        of Raymond Hettinger ([0]_) but significantly modified.
    
        Parameters
        ----------
        iterable : iterable
            The `iterable` for which to calculate the minimum and maximum.
    [...]
    

    The docstring for this function is defined this file.

    It is important to realize that this isn't possible for python < 3.4 and you need to follow some rules:

    • You need to include --\n\n after the signature definition line.

    • The signature must be in the first line of the docstring.

    • The signature must be valid, i.e. foo(a, b=1, c) fails because it's not possible to define positional arguments after arguments with default.

    • You can only provide one signature. So it doesn't work if you use something like:

      foo(a)
      foo(x, a, b)
      --
      
      Narrative documentation
      

提交回复
热议问题