Thanks to visit codestin.com
Credit goes to github.com

Skip to content

BUG: __array__ method return object itself when returning an array with single item #29161

Open
@Daraan

Description

@Daraan

Describe the issue:

I became aware of this from this recent SO question.

The expectation when returning np.array(self.data, dtype=object) inside __array__ would be to return the wrapped dict itself. However it returns the instance of the object itself.
I realized that when using ndmin=1 or [self.data] it returns the correct result, however this creates an unexpected additional dimension.

My further research showed that this happens always when returning single item array:

Reproduce the code example:

import numpy as np

class MyUserDict:
    def __array__(self, dtype=None, copy=None):
        return np.array(None, dtype=object)

arr = np.array([MyUserDict()])
print(arr)
print(type(arr[0]))

Output:

[<__main__.MyUserDict object at 0x7624203b1dd0>]
<class '__main__.MyUserDict'>

Expected:
[None]
NoneType

Python and NumPy Versions:

Tested with Python 3.10 & 3.11.
Numpy: 1.24.x & 2.2.4

Runtime Environment:

No response

Context for the issue:

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    00 - Bug57 - Close?Issues which may be closable unless discussion continued

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions