{"id":6743,"library":"numpydantic","title":"Numpydantic","description":"Numpydantic provides robust type and shape validation, and serialization capabilities for arbitrary array types (primarily NumPy arrays) within Pydantic models. It enables developers to define strict data contracts for numerical data, integrating seamlessly with Pydantic v1.x and v2.x. The current version is 1.8.1, with a consistent, active release cadence.","status":"active","version":"1.8.1","language":"en","source_language":"en","source_url":"https://github.com/astral-sh/numpydantic","tags":["pydantic","numpy","validation","serialization","data-science","type-hinting"],"install":[{"cmd":"pip install numpydantic","lang":"bash","label":"Install numpydantic"}],"dependencies":[{"reason":"Core dependency for model definition and validation, supports >=1.8,<3.0","package":"pydantic"},{"reason":"Required for array manipulation and `NDArray` type, supports >=1.20","package":"numpy"}],"imports":[{"symbol":"NDArray","correct":"from numpydantic import NDArray"}],"quickstart":{"code":"from typing import Annotated\nimport numpy as np\nfrom pydantic import BaseModel\nfrom numpydantic import NDArray\n\nclass MyModel(BaseModel):\n    image: Annotated[NDArray[(\"width\", \"height\"), \"uint8\"], \"Image data\"]\n    matrix: Annotated[NDArray[\"*,*\", float], \"Arbitrary float matrix\"]\n    vector: Annotated[NDArray[3, int], \"3-element integer vector\"]\n\n# Example usage:\ntry:\n    model = MyModel(\n        image=np.zeros((100, 200), dtype=np.uint8),\n        matrix=np.ones((2, 2), dtype=float),\n        vector=np.array([1, 2, 3], dtype=int)\n    )\n    print(\"Model created successfully:\")\n    print(model.model_dump_json(indent=2))\n\n    # Example of validation error\n    print(\"\\nAttempting invalid data:\")\n    MyModel(\n        image=np.zeros((50, 50), dtype=np.float32), # Wrong dtype\n        matrix=np.array([1, 2, 3]), # Wrong dimensions\n        vector=np.array([1, 2], dtype=int) # Wrong size\n    )\nexcept Exception as e:\n    print(f\"Caught expected error: {type(e).__name__}: {e}\")\n","lang":"python","description":"This quickstart demonstrates how to define a Pydantic model using `numpydantic.NDArray` to enforce specific array shapes and data types. It shows examples of valid model instantiation and how validation errors are caught for incorrect data."},"warnings":[{"fix":"For efficient serialization of large arrays, consider implementing custom serializers that convert arrays to a more compact format (e.g., Base64 encoded bytes, or leveraging a binary format like Parquet or HDF5) or storing only metadata (shape, dtype) and loading data separately. Pydantic's `model_dump` `mode='json'` or custom JSON encoders can be used.","message":"When serializing a Pydantic model containing `NDArray` fields (e.g., using `model_dump_json`), NumPy arrays are, by default, converted into standard Python lists (list of lists). For very large arrays, this can be extremely inefficient, consume significant memory, and result in large JSON payloads.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Always use `Annotated[NDArray[shape_spec, dtype_spec], 'description']`. The `shape_spec` should be a tuple or string (e.g., `(3, 'width')`, `\"*\"`, `\"*,*\"`), and `dtype_spec` a string (e.g., `'float'`, `'int64'`, `'uint8'`). Refer to the official `numpydantic` documentation for detailed annotation syntax.","message":"`numpydantic` heavily relies on `typing.Annotated` for specifying array shape and data type constraints. Incorrectly structuring these annotations (e.g., providing a plain tuple instead of `NDArray[(shape_tuple), (dtype_string)]`) will lead to validation errors or unexpected behavior.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Always test your models thoroughly after Pydantic version upgrades. Use `model.model_dump_json()` for serialization in Pydantic v2. Refer to Pydantic's official migration guides for comprehensive changes between major versions.","message":"While `numpydantic` aims for compatibility with both Pydantic v1.x and v2.x, subtle behavioral differences in Pydantic's core validation and serialization mechanisms might exist. For instance, `model.json()` is deprecated in Pydantic v2 in favor of `model.model_dump_json()`.","severity":"gotcha","affected_versions":"All versions, especially when migrating Pydantic versions"}],"env_vars":null,"last_verified":"2026-04-15T00:00:00.000Z","next_check":"2026-07-14T00:00:00.000Z","problems":[]}