Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Docstrings in C extensions to Python?

Tags:

When creating a C extension to Python, is it possible to be able to somehow write comments that are exposed as docstrings to users of the extension?

like image 874
Tim McNamara Avatar asked Jun 06 '11 23:06

Tim McNamara


People also ask

How do you use docstrings in Python?

Declaring Docstrings: The docstrings are declared using ”'triple single quotes”' or “””triple double quotes””” just below the class, method or function declaration. All functions should have a docstring.

How do I get Python docstrings?

Docstrings are accessible from the doc attribute (__doc__) for any of the Python objects and also with the built-in help() function. An object's docstring is defined by including a string constant as the first statement in the object's definition.

What are C extensions in Python?

Extending Python with C or C++ It is quite easy to add new built-in modules to Python, if you know how to program in C. Such extension modules can do two things that can't be done directly in Python: they can implement new built-in object types, and they can call C library functions and system calls.

Are docstrings required in Python?

Docstrings are not necessary for non-public methods, but you should have a comment that describes what the method does. This comment should appear after the "def" line.


1 Answers

Docstrings for types can be included as the tp_doc member in the PyTypeObject structure, see an example in the docs.

Docstrings for functions can be included in the ml_doc field of the module's method table. If you want your docstrings to be "physically close" to the actual functions, you could include string constants above your function definitions which you reference in the method table.

Docstrings for methods can be assigned to the doc field in the type's member table.

Docstrings for modules can be passed as a parameter to the Py_InitModule3() or Py_InitModule4() functions.


UPDATE: Python3 does not support Py_InitModule3(), and the method has been replaced with PyModule_Create().

like image 138
Sven Marnach Avatar answered Sep 27 '22 21:09

Sven Marnach