[Numpy-discussion] Unexpected attribute error
James Bergstra
bergstrj@iro.umontreal...
Wed Nov 18 11:17:57 CST 2009
On Tue, Nov 17, 2009 at 9:53 PM, Robert Kern <robert.kern@gmail.com> wrote:
> On Tue, Nov 17, 2009 at 20:48, James Bergstra <bergstrj@iro.umontreal.ca> wrote:
>> Is it by design that "numpy.sqrt(None)" raises an "AttributeError: sqrt"?
>
> Yes. numpy.sqrt() is a ufunc. Ufuncs take their arguments and try to
> convert them to numpy arrays; the manual equivalent is
> numpy.asarray(None). In this case, you get a rank-0 array with
> dtype=object. The way unary ufuncs work on object arrays is to call
> the method of the same name on the object. None.sqrt doesn't exist, so
> the AttributeError gets raised.
>
>> This was confusing because there was an attribute lookup of 'sqrt' in
>> numpy right there in the expression I typed, but that was not the
>> attribute that python was complaining about. I presume that numpy.sqrt
>> didn't know what to do with None, so it looked up a .sqrt in it or
>> something... but I presume this only in hindsight now that I figured
>> out the problem--I didn't mean to take the sqrt of None in the first place.
>>
>> How about adding some information to the AttributeError, such
>> as the object on which the lookup failed (here None, as opposed to the
>> numpy module).
>
> Patches welcome.
How about putting something like this into the scalarmathmodule.c.src
file, around line 1177?
static PyObject * _GetAttrString(PyObject * obj, const char * str)
{
PyObject * rval = PyObject_GetAttrString(obj, str);
if (!rval)
{
PyExc_SetValue(PyExc_AttributeError, Py_BuildValue("(OO)",
obj, PyString_FromString(str)))
}
return rval;
}
I'm not crystal on whether obj's refcount needs bumping, but this
function would be used instead of PyObject_GetAttrString in the
get_functions() body in that file.
I know nothing about now numpy works internally... is this remotely correct?
James
--
http://www-etud.iro.umontreal.ca/~bergstrj
More information about the NumPy-Discussion
mailing list