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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
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!-).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.