# [Numpy-discussion] recarray field access asymmetry

David Gowers (kampu) 00ai99@gmail....
Wed Feb 15 01:45:03 CST 2012

Hi all,

This email is about the difference, given a recarray 'arr',
between

A)

arr.foo.x[0]

and B)

arr.foo[0].x

Specifically, form A returns the 0-th x value, whereas form B raises
AttributeError:

Some code demonstrating this:

>>> arr = np.zeros((4,), dtype = [('foo',[('x','H'),('y','H')])])
>>> a2 = arr.view (np.recarray)
>>> a2.foo
rec.array([(0, 0), (0, 0), (0, 0), (0, 0)],
dtype=[('x', '<u2'), ('y', '<u2')])

>>> a2.foo.x
array([0, 0, 0, 0], dtype=uint16)

>>> a2.foo.x[0]
0

>>> a2.foo[0]
(0, 0)
>>> a2.foo[0].x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'numpy.void' object has no attribute 'x'

(similarly, ``a2[0].foo`` raises an identical AttributeError)

This is obstructive, particularly since ``a2.foo[0].x`` is the more
logical grouping than ``a2.foo.x[0]`` -- we want the x field of item 0
in foo, not the 0th x-value in foo.

I see this issue has come up previously...
http://mail.scipy.org/pipermail/numpy-discussion/2008-August/036429.html

The solution proposed by Travis in that email:

('arr.view(dtype=(np.record, b.dtype), type=np.recarray)')

is ineffective with current versions of NumPy; the result is exactly
the same as if you had not done it at all.
I've tried various other methods including subclassing recarray and
overriding __getitem__ and __getattribute__, with no success.

My question is, is there a way to resolve this so that ``a2.foo[0].x``
does actually do what you'd expect it to?

Thanks,
David