I am writing a simple Vector
implementation as a Python extension module in C that looks mostly like this:
typedef struct {
PyObject_HEAD
double x;
double y;
} Vector;
static PyTypeObject Vector_Type = {
...
};
It is very simple to create instances of Vector
while calling from Python, but I need to create a Vector
instance in the same extension module. I looked in the documentation but I couldn't find a clear answer. What's the best way to do this?
Simplest is to call the type object you've created, e.g. with PyObject_CallFunction -- don't let the name fool you, it lets you call any callable, not just a function.
If you don't have a reference to your type object conveniently available as a
static
global to your C module, you can retrieve it in various ways, of course (e.g., from your module object with a PyObject_GetAttrString). But sticking thatPyObject*
into astatic
module-level C variable is probably simplest and most convenient.