From daniele at grinta.net Tue Jun 16 16:32:47 2020 From: daniele at grinta.net (Daniele Nicolodi) Date: Tue, 16 Jun 2020 14:32:47 -0600 Subject: [Cython] Most efficient way to create an object with Python C-API Message-ID: <9788e088-8893-c53a-0e3a-fed8f82f072e@grinta.net> Hello, this is not a question directly related to cython, but I think the readers of this list may have the right expertise to answer it. I am working on a Python extension where I need to instantiate a lot of Decimal objects. I would like to make it as efficient as possible. Unfortunately the C-API of the _decimal module is not exposed (as is for example done for the datetime module). The straightforward approach is something on the lines of: PyObject* decimal = PyImport_ImportModule("decimal"); PyObject* constructor = PyObject_GetAttrString(m, "Decimal"); and then instantiate the objects with something like: PyObject* obj = PyObject_CallFunction(PyDec_Type, "s#", str, len); Is there a better way? I was thinking about getting to the PyTypeObject for Decimal, like PyTypeObject* type = Py_TYPE(obj); but then I don't see an easy way to use it to instantiate an object. Am I missing something? Thank you. Cheers, Dan From greg.ewing at canterbury.ac.nz Wed Jun 17 18:10:18 2020 From: greg.ewing at canterbury.ac.nz (Greg Ewing) Date: Thu, 18 Jun 2020 10:10:18 +1200 Subject: [Cython] Most efficient way to create an object with Python C-API In-Reply-To: <9788e088-8893-c53a-0e3a-fed8f82f072e@grinta.net> References: <9788e088-8893-c53a-0e3a-fed8f82f072e@grinta.net> Message-ID: <14aecc99-8def-e5cb-e2b7-d312dd6f557e@canterbury.ac.nz> On 17/06/20 8:32 am, Daniele Nicolodi wrote: > PyObject* decimal = PyImport_ImportModule("decimal"); > PyObject* constructor = PyObject_GetAttrString(m, "Decimal"); > PyObject* obj = PyObject_CallFunction(PyDec_Type, "s#", str, len); > > Is there a better way? > > I was thinking about getting to the PyTypeObject for Decimal, like > > PyTypeObject* type = Py_TYPE(obj); That will get you exactly the same object you get by importing the decimal.Decimal class. In Python3 there is no difference between a type and a class. So I don't think there's any substantially faster way. -- Greg