Ania
Ania

Reputation: 115

How to declare numpy array of particular type as type in dataclass

What I have:
I am creating a dataclass and I am stating the types of its elements:

class Task():  
     n_items: int  
     max_weight: int  
     max_size: int  
     items: numpy.array(Item)  # incorrect way of doing it

What I want to do
I'd like to declare, that items will be a numpy array of obejcts of class "Item"

Upvotes: 6

Views: 14995

Answers (3)

sigma
sigma

Reputation: 216

You can use the nptyping package, which offers type hints specifically for Numpy data types.

Unless you want to create a custom Numpy container, the best you can do is to denote your array as a container of typing.Any objects, since support for types beyond the ones mentioned here is lacking.

from nptyping import NDArray, Shape
from typing import Any
import numpy as np


class Item:
    pass


class Foo:
    def __init__(self, bar: NDArray[Shape["1,2"], Any]):
        self.bar = bar


if __name__ == '__main__':
    item = Item()
    foo = Foo(bar=np.array([Item(), Item()], dtype=Item))
    print(foo.bar)

Running this will yield something like

[<__main__.Item object at 0x7f13f0dd9e80>
 <__main__.Item object at 0x7f13f0dd9040>]

Upvotes: 1

Lucas Cauh&#233;
Lucas Cauh&#233;

Reputation: 96

You have to use ndarray class type:

import numpy as np

class Task():  
     n_items: int  
     max_weight: int  
     max_size: int  
     items: np.ndarray[<shapeType>, <convertedNumpyGenericType>]

Where <shapeType> is the type of values defining the shape of the array (probably int) and <convertedNumpyGenericType> defines the array data's type. Be careful that you have to "convert" numpy generic types into python ones. You may want to use np.dtype[<generic>] with <generic> the generic numpy type (e.g np.float64)

If you want to set a default value (inside the field dataclass function) you have to do as follows:

items: np.ndarray[_, _] = field(default_factory=lambda: np.zeros(shape=<int>, dtype=<type>))

Upvotes: 3

Georgina Skibinski
Georgina Skibinski

Reputation: 13387

You can put ndarray:

import numpy as np

class Task():  
     n_items: int  
     max_weight: int  
     max_size: int  
     items: np.ndarray

Upvotes: 5

Related Questions