[Numpy-discussion] __getitem__ and creating an array of objects

Aldcroft, Thomas aldcroft at head.cfa.harvard.edu
Thu May 30 16:21:36 EDT 2013

I'm seeing some behavior that I can't understand when creating a numpy
array of Python objects.  Basically it seems that np.array() is calling the
object __getitem__ method for one object class but not another class, and I
can't understand the difference.

Here is an example, starting with a simple class where __getitem__ does NOT
get called:

>>> class Foo(object):
...     def __getitem__(self, item):
...         return 1/0
...     def __len__(self, item):
...         return 1
>>> f = Foo()
>>> x = np.array([f])
>>> x
array([<__main__.Foo object at 0x11a1ff10>], dtype=object)

Now move to the complicated class (astropy.time.Time) which has a lot of
stuff in it (including __new__, __init__, and __len__ methods, but
initially no __getitem__), but is otherwise an ordinary class derived from
object. This works as expected:

>>> from astropy.time import Time
>>> t = Time('2001-01-01', scale='utc')
>>> x = np.array([t])
>>> x
array([2001-01-01 00:00:00.000], dtype=object)

Now inject a __getitem__ that will fail and try again:

>>> Time.__getitem__ = lambda self, item: 1 / 0
>>> x = np.array([t])
ERROR: ZeroDivisionError: integer division or modulo by zero

Any ideas on what is driving this difference in behavior?  BTW, the value
of item in the latter case is 0.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20130530/b6e4c54d/attachment.html>

More information about the NumPy-Discussion mailing list