Skip to content

Why does __array_priority__ not take precedence over __array__? #3164

@astrofrog

Description

@astrofrog

If I run the following dummy example:

import numpy as np

class MyCustomClass(object):

    __array_priority__ = 1000

    def __array__(self):
        return np.array([1,2,3])

    def __mul__(self, other):
        return np.array([4,5,6])

    def __rmul__(self, other):
        return self.__mul__(other)

c = MyCustomClass()

print(np.array([1]) * c)
print(c * np.array([1]))

I get

[1 2 3]
[4 5 6]

which in my view is incorrect (__array__ should not get called because __array_priority__ is higher than that for np.array([1])). If I remove the __array__ method, I get the expected result:

[4 5 6]
[4 5 6]

as expected. This suggests to me that the presence of __array__ takes precedence over the __array_priority__. Is there a reason for this, or is it an oversight?

Most importantly, is there a way to get around this, and ensure that if __array__ is present, __rmul__ still gets called?

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