Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

pydantic numpy ndarray type

# Define custom type validatable by Pydantic.
class TypedArray(numpy.ndarray):
    @classmethod
    def __get_validators__(cls):
        yield cls.validate_type

    @classmethod
    def validate_type(cls, val):
        return numpy.array(val, dtype=cls.inner_type)

class ArrayMeta(type):
    def __getitem__(self, t):
        return type('Array', (TypedArray,), {'inner_type': t})

class Array(numpy.ndarray, metaclass=ArrayMeta):
    pass

class Model(BaseModel):
    values: Array[float]

m = Model(values=[1, 2, 3])
print(m)
Source by github.com #
 
PREVIOUS NEXT
Tagged: #pydantic #numpy #ndarray #type
ADD COMMENT
Topic
Name
7+6 =