recarray.__setattr__ bug?

Michael McNeil Forbes mforbes at phys.washington.edu
Fri Oct 27 22:18:52 EDT 2006


Is the following the desired behaviour for setting recarray attributes?  
This seems to clash with the semantics for arrays.

 >>> from numpy import *
 >>> a = array([1,2,3])
 >>> b = a.view([('x',int),('y',int),('z',int)])
 >>> r = b.view(recarray)
 >>> b['x'] = 0
 >>> r.y = 0
 >>> a
 array([0, 2, 3])
 >>> r.x
 array([0])
 >>> r.y
 0

Setting r.y creates a local variable in r.__dict__ which is then 
accessed rather than the array element referred to by fielddict.

I am not sure how to fix this: trying to set an attribute that does not 
exist in an ndarray raises an error, so I figured that changing the 
second line of recarray.__setattr__ in numpy/core/records.py to

    def __setattr__(self, attr, val):
        try:
            return sb.ndarray.__setattr__(self, attr, val)

would work, but this sets the variable in r.__dict__ (and I am not 
exactly sure where this is defined, so I can't comment further).  Is 
there a simple solution like this or does one need to explicitly check 
'__dict__'.

One could reverse the order and call 'setfield' if the value is in the 
'fielddict' first and then revert to the base setter, but this would 
potentially hide other members like 'shape'.  (Making this change does 
not break any tests however.)

A test case for this would be:

    def check_recarray_setattr1(self):
        """Make sure __setattr__ sets array fields."""
        a = array([1,2])
        r = rec.fromarrays(a,names=['x','y'])
        b = a.view(r.dtype).view(recarray)
        b.x = 0
        assert 0 == a[0]

    def check_recarray_setattr2(self):
        """Make sure shape attribute is not hidden."""
        a = array([[1,2],[3,4]])
        r = rec.fromarrays(a,names=['x','shape'])
        b = a.view(r.dtype).view(recarray)
        assert 3 == b[1,0][0]
        b.shape = (1,2)
        assert 3 == b[0,1][0]

Michael.


-------------- next part --------------
-------------------------------------------------------------------------
Using Tomcat but need to do more? Need to support web services, security?
Get stuff done quickly with pre-integrated technology to make your job easier
Download IBM WebSphere Application Server v.1.0.1 based on Apache Geronimo
http://sel.as-us.falkag.net/sel?cmd=lnk&kid=120709&bid=263057&dat=121642
-------------- next part --------------
_______________________________________________
Numpy-discussion mailing list
Numpy-discussion at lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/numpy-discussion


More information about the NumPy-Discussion mailing list