Skip to content

feat: add numpy array and scalar types (Fixes #31) - #425

Open
mukktinaadh wants to merge 1 commit into
pydantic:mainfrom
mukktinaadh:main
Open

mukktinaadh wants to merge 1 commit into
pydantic:mainfrom
mukktinaadh:main

Conversation

@mukktinaadh

Copy link
Copy Markdown

Summary

This PR adds numpy array and scalar types to pydantic-extra-types, implementing the feature requested in issue #31.

Changes

New Types Added

  1. NumpyArray - A wrapper type that validates numpy.ndarray objects with optional dtype and shape constraints

    • Supports optional dtype constraint (e.g., dtype=np.float64)
    • Supports optional shape constraint with -1 for flexible dimensions (e.g., shape=(3, -1))
    • Works with both generic np.ndarray annotation and Annotated[np.ndarray, NumpyArrayValidator(...)]
  2. NumpyScalar - A wrapper type that validates numpy scalar types (np.generic)

    • Supports optional dtype constraint
    • Works with np.int64, np.float64, etc.
  3. NumpyArrayValidator - An annotation for use with Annotated[np.ndarray, NumpyArrayValidator(...)]

    • Supports dtype and shape parameters
    • Can be used with Annotated[np.ndarray, NumpyArrayValidator(dtype=np.float64, shape=(3, 3))]

Features

  • Dtype validation: Validates that arrays/scalars have the expected dtype
  • Shape validation: Supports fixed shapes and flexible dimensions (using -1 for any size)
  • Clear error messages: Detailed error messages showing what failed (dtype mismatch, shape mismatch, wrong dimensions)
  • Full pydantic integration: Works with Annotated, TypeAdapter, and model fields
  • Comprehensive documentation: Each type includes comprehensive docstrings with examples

Testing

All existing tests pass. The implementation includes:

  • NumpyArray with dtype and shape validation
  • NumpyScalar for numpy scalar types
  • NumpyArrayValidator for use with Annotated
  • Proper error messages for dtype mismatches, shape mismatches, and dimension mismatches
  • Support for flexible dimensions using -1 in shape tuples
  • Support for both class-based and Annotated usage patterns

Fixes #31

- Add NumpyArray type for validating numpy.ndarray with optional dtype and shape constraints
- Add NumpyScalar type for validating numpy scalar types
- Add NumpyArrayValidator for use with Annotated[np.ndarray, NumpyArrayValidator(...)]
- Add proper validation for dtype and shape constraints
- Include comprehensive docstrings with examples

Fixes pydantic#31

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support numpy types

1 participant