[Numpy-discussion] ndarray __getattr__ to perform __getitem__

Ian Stokes-Rees ijstokes at hkl.hms.harvard.edu
Fri Oct 29 09:58:33 EDT 2010


> Note that there are various extant projects that I think attempt to  
> provide similar functionality to what you're wanting (unless I badly  
> misread your original email, in which case apologies):
> http://projects.scipy.org/numpy/wiki/NdarrayWithNamedAxes

Having looked into it more, I think recarray is probably what I want.  I
need to play with this and see how easy it is to convert ndarrays into
recarrays.

The main thing is that I'm looking for something *really* simple that
would, truly, just allow the conversion of:

myarray['myaxis']

to

myarray.myaxis

My suggestion is to define __getattr__ directly on the ndarray class. 
This is, TTBOMK, only called if an attribute is *not* found on the
object.  In this event, prior to throwing an AttributeError exception,
the object could check to see if the specified attribute exists as a
named axis/dimension of the multi-dimensional array, and if so, return
this.  Otherwise, carry on with the AttributeError exception.

I've spent an hour looking at the numpy code (my first time), and I
don't see any obvious way to do this, since ndarray is (AFAICT) a pure-C
object with auto-generated wrappers, which seems to preclude (easily)
adding a "__getattr__(self,attr)" method to the class.  If someone can
point me in the right direction, I'll keep looking into this, otherwise
I'm giving up and will just try and use recarray.

Ian



More information about the NumPy-Discussion mailing list