Normally it's possible to put arbitrary objects into numpy arrays:
class Foo(object):
pass
np.array([ Foo() ])
>>> array([<__main__.Foo object at 0x10d7c3610>], dtype=object)
However, it appears that objects implementing __len__ and __getitem__ are "unpacked" automatically:
class Foo(object):
def __len__(self): return 3
def __getitem__(self, i): return i*11
np.array([ Foo() ])
>>> array([[0, 11, 22]])
Is there any way to stop numpy from unpacking objects in this way? What I want is to put some objects into a numpy array and have them be stored as the objects themselves, without being unpacked. So the desired behavior is:
class Foo(object):
def __len__(self): return 3
def __getitem__(self, i): return i*11
np.array([ Foo() ])
>>> array([<__main__.Foo object at 0x10d7c3610>], dtype=object)
Now I understand that the duck typing idea implies that numpy should unpack anything that looks like a list. But perhaps it's possible to mark the class Foo in some way to tell numpy not to unpack it? For example, an ABC like:
numpy.Nonenumerable.register(Foo)