[Numpy-discussion] ndarray __getattr__ to perform __getitem__

Pierre GM pgmdevlist at gmail.com
Fri Oct 29 10:23:24 EDT 2010


On Oct 29, 2010, at 3:58 PM, Ian Stokes-Rees wrote:

> 
>> 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.

your_rec=your_array.view(np.recarray)


> 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

Attribute-style access is IMHO the only interest of recarrays over regular structured arrays. Note that it comes to a cost...


> 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.

Indeed. Check how recarray does it, for example.





More information about the NumPy-Discussion mailing list