3

Can I cast a python class to a numpy array?

from dataclasses import dataclass
import numpy as np
@dataclass
class X:
    x: float = 0
    y: float = 0
x = X()
x_array = np.array(x) # would like to get an numpy array np.array([X.x,X.y])

In the last step, I would like the to obtain an array np.array([X.x, X.y]). Instead, I get array(X(x=0, y=0), dtype=object).

Can I provide method for the dataclass so that the casting works as desired (or overload one of the existing methods of the dataclass)?

4
  • try to add def __iter__(self): yield from (self.x, self.y) Commented Nov 30, 2020 at 9:00
  • Thanks for your suggestion @AzatIbrakov ! I did try but to no avail. Maybe I defined it the wrong way. Can you provide a fully specified answer? Commented Nov 30, 2020 at 9:07
  • 1
    it was a wrong suggestion based only on intuition, after reading a docstring of numpy.array it is clear that you can define __array__ method like def __array__(self): return np.array([self.x, self.y]) Commented Nov 30, 2020 at 9:19
  • Thanks @AzatIbrakov ! This is really helpful. Do you want to write an answer so that I can accept? Commented Nov 30, 2020 at 9:25

1 Answer 1

8

From docstring of numpy.array we can see requirements for the first parameter

object: array_like

An array, any object exposing the array interface, an object whose __array__ method returns an array, or any (nested) sequence.

So we can define an __array__ method like

@dataclass
class X:
    x: float = 0
    y: float = 0

    def __array__(self) -> np.ndarray:
        return np.array([self.x, self.y])

and it will be used by np.array. This should work for any custom Python class I guess.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.