[Numpy-discussion] ndarray __getattr__ to perform __getitem__
Ian Stokes-Rees
ijstokes@hkl.hms.harvard....
Thu Oct 28 15:17:08 CDT 2010
I have an ndarray with named dimensions. I find myself writing some
fairly laborious code with lots of square brackets and quotes. It seems
like it wouldn't be such a big deal to overload __getattribute__ so
instead of doing:
r = genfromtxt('results.dat',dtype=[('a','int'), ('b', 'f8'),
('c','int'), ('d', 'a20')])
scatter(r[r['d'] == 'OK']['a'], r[r['d'] == 'OK']['b'])
I could do:
scatter(r[r.d == 'OK'].a, r[r.d == 'OK'].b)
which is really a lot clearer. Is something like this already possible
somehow?
Is there some reason not to map __getattr__ to __getitem__?
class ndarray():
...
__getattr__ = __getitem__
Or something somewhat more sophisticated like:
def __getattr__(self, attr):
if self.hasitem(attr):
return self[attr]
else:
raise AttributeError(attr)
TIA for any comments or thoughts on this.
Ian
More information about the NumPy-Discussion
mailing list