8000 assert_equal gives KeyError: 0 for some Python objects. · Issue #5285 · numpy/numpy · GitHub
[go: up one dir, main page]

Skip to content
assert_equal gives KeyError: 0 for some Python objects. #5285
Closed
@mdickinson

Description

@mdickinson

In NumPy 1.9, numpy.testing.assert_equal can raise a KeyError in some cases. An example is below. It's not as minimal as I would like: I was unable to easily remove the dependence on the Traits library.

from UserDict import DictMixin
from numpy.testing import assert_equal
from traits.api import HasTraits


class DataContext(DictMixin, HasTraits):
    def __init__(self):
        self.subcontext = {}

    def __getitem__(self, key):
        return self.subcontext[key]

    def __setitem__(self, key, value):
        self.subcontext[key] = value

    def keys(self):
        return self.subcontext.keys()


# This code works.
a = DataContext()
a['foo'] = 2
a['bar'] = 3
assert_equal(a, a)

# But this doesn't: the call to `assert_equal` gives `KeyError: 0`.
c = DataContext()
c['foo'] = 1
assert_equal(c, c)

The above code fails for me under NumPy 1.9 (but not NumPy 1.8), with the following output:

(.devenv)taniyama:Desktop mdickinson$ python numpy_bug.py 
Traceback (most recent call last):
  File "numpy_bug.py", line 31, in <module>
    assert_equal(c, c)
  File "/Users/mdickinson/Enthought/Source/meta-geophysics/.devenv/lib/python2.7/site-packages/numpy/testing/utils.py", line 282, in assert_equal
    usecomplex = iscomplexobj(actual) or iscomplexobj(desired)
  File "/Users/mdickinson/Enthought/Source/meta-geophysics/.devenv/lib/python2.7/site-packages/numpy/lib/type_check.py", line 269, in iscomplexobj
    return issubclass(asarray(x).dtype.type, _nx.complexfloating)
  File "/Users/mdickinson/Enthought/Source/meta-geophysics/.devenv/lib/python2.7/site-packages/numpy/core/numeric.py", line 462, in asarray
    return array(a, dtype, copy=False, order=order)
  File "numpy_bug.py", line 13, in __getitem__
    return self.subcontext[key]
KeyError: 0

I have no idea why the array constructor would be trying to access item 0 of this object, but I can imagine that there might be valid reasons for doing so. If so, it might be useful to turn the except ValueError for the use_complex section of the assert_equal code into except (KeyError, ValueError). (Code here).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0