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()
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=...).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With