[Python-Dev] when is path==NULL?
Thomas Lee
tom at vector-seven.com
Tue Sep 30 14:42:11 CEST 2008
Ulrich Eckhardt wrote:
> Hi!
>
> I'm looking at trunk/Python/sysmodule.c, function PySys_SetArgv(). In that
> function, there is code like this:
>
> PyObject* path = PySys_GetObject("path");
> ...
> if (path != NULL) {
> ...
> }
>
> My intuition says that if path==NULL, something is very wrong. At least I
> would expect to get 'None', but never NULL, except when out of memory. So,
> for the case that path==NULL', I would simply invoke Py_FatalError("no mem
> for sys.path"), similarly to the other call there.
>
> Sounds reasonable?
>
> Uli
>
>
Maybe it's just being safe?
From Python/sysmodule.c:
PyThreadState *tstate = PyThreadState_GET();
PyObject *sd = tstate->interp->sysdict;
if (sd == NULL)
return NULL;
return PyDict_GetItemString(sd, name);
So if tstate->interp->sysdict is NULL, we return NULL. That's probably a
bit unlikely.
However, PyDict_GetItemString attempts to allocate a new PyString from
the given char* key. If that fails, PySys_GetObject will also return
NULL -- just like most functions in the code base that hit an out of
memory error:
PyObject *
PyDict_GetItemString(PyObject *v, const char *key)
{
PyObject *kv, *rv;
kv = PyString_FromString(key);
if (kv == NULL)
return NULL;
rv = PyDict_GetItem(v, kv);
Py_DECREF(kv);
return rv;
}
Seems perfectly reasonable for it to return NULL in this situation.
Cheers,
T
More information about the Python-Dev
mailing list