Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a new type (class) in Python using C API?

Tags:

python

c

class

I am trying to use the Python C API to define a new class inside a module that would expose certain functionality written in C to Python code. I specifically want to have it in the form of a class and not a set of module functions.

However, I can't find anything regarding this particular task in the official documentation. The closest I could find is PyClass_New function (in the Python.h header) but it is not mentioned anywhere in the official docs, so I assume it is not supposed to be used.

So, what is the proper way to define a new Python class from C code?

Thanks.

like image 785
user352864 Avatar asked Jun 07 '10 14:06

user352864


People also ask

What is C API in Python?

The Python/C API allows for compiled pieces of code to be called from Python programs or executed within the CPython interpreter. This process of producing compiled code for use by CPython is generally known as "extending" Python and the compiled pieces of code to be used are known as "extension modules".


1 Answers

This part of the docs (and surrounding ones) should give you most of the info you need. The xxsubtype.c sources provide one example module that defines a new class (as a subclass of list, to show precisely how to do that, too) and xxmodule.c shows (among many other things) also how to define a new type.

like image 107
Alex Martelli Avatar answered Oct 10 '22 10:10

Alex Martelli