char** to {'':('',)}
Ignacio Vazquez-Abrams
ignacio at openservices.net
Wed Aug 29 16:35:32 EDT 2001
On Wed, 29 Aug 2001, Tim Peters wrote:
> [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".
Unfortunately I have even more pragmatic a reason for doing it in C than
speed; I get the char** for a library written in C, and some days it's just
NOT worth using the struct module.
And don't take this the wrong way, but I refuse to use goto. No, don't bother
arguing; there's no point.
> > ...
> > 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.
Yeah, I caught that one a couple of hours after posting.
> practicality-beats-purity-ly y'rs - tim
Pfft! You don't know me very well, do you? ;)
> 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>).
Heh :) I just needed an error message so that I could be certain that I
wouldn't get that silly "No exception was set" message.
I've noticed two big holes in the Python/C API:
1) It doesn't say for all functions which ones set exceptions, and
2) It doesn't say for all functions whether or not they increment refcounts of
objects passed to them, viz. PyDict_SetString().
--
Ignacio Vazquez-Abrams <ignacio at openservices.net>
More information about the Python-list
mailing list