[Numpy-discussion] Unexpected attribute error

Charles R Harris charlesr.harris@gmail....
Wed Nov 18 11:48:35 CST 2009


On Wed, Nov 18, 2009 at 10:17 AM, James Bergstra
<bergstrj@iro.umontreal.ca>wrote:

> 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?
>
>
Looks about right to get a more informative error message. What happens when
you compile with it and run the tests? What does the output of you example
look like?

Chuck
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/numpy-discussion/attachments/20091118/0810fe91/attachment.html 


More information about the NumPy-Discussion mailing list