Finding a python object in c++

Alex Martelli aleaxit at yahoo.com
Fri Sep 17 18:14:59 EDT 2004


Brian Matt <bsmatt at gmail.com> wrote:
   ...
> //Assume python initialized and module imported
> dict = PyModule_GetDict(module);
> PyObject* pInst = PyDict_GetItemString(dict, "f1");

OK, but needlessly indirect.  Doing just:

PyObject* pInst = PyObject_GetAttrString(module, "f1");

should, I think, be preferable.

> if(pInst) {
>       PyObject *pValue;
>       pValue = PyObject_CallMethod(pInst, "func", "");
>       if(pValue) {
>               Py_DECREF(pValue);
>       }
> }
> 
> Note: this code doesn't handle error situations like making sure the
> pInst variable is an instance object

So much the better!  If module.f1 has a func method that is callable
without arguments, why ever would you want to prohibit it from being
whatever type it wants to be?  Maybe one day you'll want to recode the
whole type in C, and if you'd gone to the misplaced trouble of "making
sure [it] is an instance object" you'd just be creating headaches for
yourself...


Alex



More information about the Python-list mailing list