1 import numpy as np
2 def make_obarray(klass, dtype):
3 class Obarray(np.ndarray):
4 def __new__(cls, obj):
5 A = np.array(obj,dtype=np.object)
6 N = np.empty(shape=A.shape, dtype=dtype)
7 for idx in np.ndindex(A.shape):
8 for name, type in dtype:
9 N[name][idx] = type(getattr(A[idx],name))
10 return N.view(cls)
11 def __getitem__(self, idx):
12 V = np.ndarray.__getitem__(self,idx)
13 if np.isscalar(V):
14 kwargs = {}
15 for i, (name, type) in enumerate(dtype):
16 kwargs[name] = V[i]
17 return klass(**kwargs)
18 else:
19 return V
20 def __setitem__(self, idx, value):
21 if isinstance(value, klass):
22 value = tuple(getattr(value, name) for name, type in dtype)
23
24 return np.ndarray.__setitem__(self, idx, value)
25 return Obarray
, as shown below in the list of files. Do
link, since this is subject to change and can break easily.