C API HowTo ? accessing objects described by dotted string from a (PyObject * )

Martin v. Löwis martin at v.loewis.de
Thu Dec 18 22:18:12 CET 2003

mhoegeman at ixiacom.com (Mike Hoegeman) writes:

> -- i have a PyObject * that is a instance of an object
> -- i need to access a subobject of that (PyObject *) that is 
>    described to me as a dotted string, e.g.:
>    "subobject1.listsubobject2[-1].subobject3"
> In other words, I need to get 
>    self.subobject1.listsubobject2[0].subobject3
> where 'self' is the (PyObject *) I have in my C Program
> do i have to parse the string and do the C API getattr calls myself
> or is there some easier way to do it?

You could evaluate the string. As this is relative to an object, you
would first rephrase this as


Then you build a dictionary where 'self' refers to that object
(PyDict_New, PyDict_SetItemString), then you evaluate the
expression in the context of the dictionary. This, in turn,
is done by invoking Py_CompileString and PyEval_EvalCode.

Notice that executing arbitrary untrusted code is a security risk.


More information about the Python-list mailing list