1

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?

Brad Zeis
  • 10,085
  • 5
  • 26
  • 20

1 Answers1

3

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 that PyObject* into a static module-level C variable is probably simplest and most convenient.

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
  • When I call Vector_Type, what function is it actually calling? Do I pass the same arguments that you would normally use to create an instance from Python? Do I also need to Py_INCREF() the returned PyObject* from PyObject_CallFunction? – Brad Zeis Apr 04 '10 at 00:04
  • When you call a type (or any other callable) from C via a `PyObject_Call...` function in the Python C API, it will go through exactly the same steps (and require exactly the same arguments) as when called from Python. The docs I pointed to clearly say _Return value: New reference._ meaning that you don't need to incref it (understanding new, borrowed and stolen references is crucial to programming to the C Python API, and the docs are always commendably super-explicit about what case applies!-). – Alex Martelli Apr 04 '10 at 00:12