Skip to content

BUG: TYPE_setitem functions are broken in various ways #8902

Closed

Description

@eric-wieser

Multiple bugs in one issue:

  • LONGDOUBLE_setitem loses precision

    tiny = np.nextafter(np.longdouble(0), 1)
    assert tiny.itemsize > 8, "requires longdouble to test"
    tiny_arr1d = np.array([tiny])
    assert tiny_arr1d[0] != 0
    tiny_arr1d[0] = tiny_arr1d[0]
    assert tiny_arr1d[0] != 0
    tiny_arr1d[0,...] = tiny_arr1d[0,...]
    assert tiny_arr1d[0] != 0
    tiny_arr1d[0] = tiny_arr1d[0,...]  # forces a pass through `float()`, which discards precision
    assert tiny_arr1d[0] != 0  # AssertionError
  • UNICODE_setitem goes via array.__str__() (causing Unicode scalar problem  #5049 on python 2.7):

    from contextlib import contextmanager
    from numpy.core.numeric import set_string_function
    
    @contextmanager
    def inject_str(s):
        set_string_function(lambda x: s, repr=False)
        try:
            yield
        finally:
            set_string_function(None, repr=False)
    
    q = np.array([u'abc'])
    q0 = np.array(u'def')
    with inject_str('WAT'):
        q[0] = q0
    assert q[0] == q0  # AssertionError: it's WAT instead
  • UNICODE_setitem and STRING_setitem behave differently when __len__ fails

    class broken:
        def __len__(self):
            raise ValueError('no length')
        def __repr__(self):
            return 'OK'
        def __getitem__(self, i):
            return 42
    
    u = np.array([u'test'])
    u[0] = broken()
    assert u[0] == 'OK'
    
    b = np.array([b'test'])
    b[0] = broken()
    # ValueError: cannot set an array element with a sequence

    Arguably the correct thing to do is just propagate the exception

  • UNICODE_setitem and STRING_setitem have a weird special cases for empty sequences:

    s = np.array(["test"])
    s[0] = []
    assert s[0] == "[]"
    s[0] = [1]
    # ValueError: setting an array element with a sequence

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions