Skip to content

Validation error with str Enum field and numpy's str_ type #9265

@maxsch3

Description

@maxsch3

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

I'm having this issue in the API that uses machine learning (numpy+scikit-learn+xgboost) to generate predictions. The predictions are text labels. The ML part returns predictions as numpy-specific strings of type str_.

These values trigger validation error when used in the ENUM fields in pydantic model:

animal
  Input should be 'dog' or 'cat' [type=enum, input_value='cat', input_type=str_]
    For further information visit https://errors.pydantic.dev/2.7/v/enum

Example Code

from enum import Enum
from pydantic import BaseModel, Field
import numpy as np


class Animal(Enum):

    dog = "dog"
    cat = "cat"


class ModelStr(BaseModel):
    animal: str = Field(..., description="A type of animal")


class ModelEnum(BaseModel):
    animal: Animal = Field(..., description="A type of animal")


numpy_array = np.array(["cat", "dog"])

# this works
ModelStr(animal=numpy_array[0])

# this triggers error
ModelEnum(animal=numpy_array[0])

Python, Pydantic & OS Version

pydantic version: 2.7.0
        pydantic-core version: 2.18.1
          pydantic-core build: profile=release pgo=true
                 install path: /home/max/Code/Drax/dev/role-classification/venv/lib/python3.10/site-packages/pydantic
               python version: 3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0]
                     platform: Linux-5.15.0-102-generic-x86_64-with-glibc2.35
             related packages: fastapi-0.101.1 typing_extensions-4.8.0
                       commit: unknown

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug V2Bug related to Pydantic V2

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions