char** to {'':('',)}
Tim Peters
tim.one at home.com
Wed Aug 29 16:21:42 EDT 2001
[Ignacio Vazquez-Abrams]
> I am using the following blecherous code to do a conversion from
> char*s in the form "<a>=<b>" to the form {'<a>':(tuple of '<b>'s), ...}.
> I'm sure that there's probably a more straightforward way out there.
> Does anyone have any ideas as to how I can simplifiy this?
Ya, write it in Python -- coding in C is a PITA. If you need to do it in C
for speed (whatever), don't be afraid of gotos! The Python implementation
has many examples of this, jumping to an error label at the end when things
go wrong "in the middle".
> ...
> PyObject *dict=NULL, *list=NULL;
> ...
> i=0;
> while(PyDict_Next(dict, &i, &key, &val))
> {
> PyDict_SetItem(result, key, PyList_AsTuple(val));
> };
>
> return result;
> };
It looks like you're letting dict leak in the normal case, and gotos help
prevent mistakes like that too.
initialize PyObject* temp thingies to NULL, and result
...
if (something_bad_happened) {
*maybe* set an exception;
goto error;
}
...
while(PyDict_Next(dict, &i, &key, &val)) {
PyDict_SetItem(result, key, PyList_AsTuple(val));
goto normal_return;
error:
Py_XDECREF(result);
result = NULL;
/* fall through */
normal_return:
Py_XDECREF(dict);
...
Py_XDECREF(other_temps);
return result;
practicality-beats-purity-ly y'rs - tim
BTW, in cases like this:
val=PyString_FromString(equals+1);
if (val==NULL)
{
PyErr_SetString(MyError, "Something else most blecherous happened!");
Py_XDECREF(dict);
Py_XDECREF(result);
return NULL;
};
PyString_FromString will already have set an appropriate exception
explaining the difficulty, so it's more work *and* usually harmful to make
up your own msg (proof: just *read* your msg above <wink>).
Follow the advice above and this whole block reduces to
val = PyString_FromString(equals+1);
if (val == NULL)
goto error;
More information about the Python-list
mailing list