Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pydantic initialize numpy ndarray

how can I initialize a ndarray when using pydantic?
This code throws a ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

from pydantic.dataclasses import dataclass
import numpy as np

@dataclass
class TestNumpyArray:
    numpyArray: np.ndarray = np.zeros(10)

testNumpyArray = TestNumpyArray()
like image 636
juerg Avatar asked Jun 20 '26 16:06

juerg


1 Answers

You'll want to provide a default_factory to a Field declaration.

Note that you can't use arbitrary types in a Pydantic dataclass, so you'll probably want to extend BaseModel:

from pydantic import BaseModel, Field
import numpy as np

class TestNumpyArray(BaseModel):
    numpyArray: np.ndarray = Field(default_factory=lambda: np.zeros(10))

    class Config:
        arbitrary_types_allowed = True

testNumpyArray = TestNumpyArray()

You can also use a non-Pydantic dataclass with dataclasses.field(default_factory=...).

like image 68
jkinkead Avatar answered Jun 23 '26 05:06

jkinkead



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!