Skip to content

Seamlessly integrate numpy arrays into pydantic models.

License

Notifications You must be signed in to change notification settings

JonathanPlasse/pydantic-numpy

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

55 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Build Status

pydantic-numpy

This library provides support for integrating numpy np.ndarray's into pydantic models.

Usage

For more examples see test_ndarray.py

from pydantic import BaseModel

import pydantic_numpy.dtype as pnd
from pydantic_numpy import NDArray, NDArrayFp32


class MyPydanticNumpyModel(BaseModel):
    K: NDArray[pnd.float32]
    C: NDArrayFp32  # <- Shorthand for same type as K


# Instantiate from array
cfg = MyPydanticNumpyModel(K=[1, 2])
# Instantiate from numpy file
cfg = MyPydanticNumpyModel(K={"path": "path_to/array.npy"})
# Instantiate from npz file with key
cfg = MyPydanticNumpyModel(K={"path": "path_to/array.npz", "key": "K"})

cfg.K
# np.ndarray[np.float32]

Subfields

This package also comes with pydantic_numpy.dtype, which adds subtyping support such as NDArray[pnd.float32]. All subfields must be from this package as numpy dtypes have no Pydantic support.

Install

Via github

pip install git+https://github.com/cheind/pydantic-numpy.git

Via PyPi (note that the package might be outdated)

pip install pydantic-numpy

History

The original idea originates from this discussion, but stopped working for numpy>=1.22. This repository picks up where the previous discussion ended

  • added designated repository for better handling of PRs
  • added support for numpy>1.22
  • Dtypes are no longer strings but np.generics. I.e. NDArray['np.float32'] becomes NDArray[np.float32]
  • added automated tests and continuous integration for different numpy/python versions

About

Seamlessly integrate numpy arrays into pydantic models.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Python 100.0%