python type_error ai_generated true

pydantic.errors.PydanticSchemaGenerationError: 无法为 <class 'numpy.ndarray'> 生成 pydantic-core 模式。请在 model_config 中设置 arbitrary_types_allowed=True 或实现 __get_pydantic_core_schema__。

pydantic.errors.PydanticSchemaGenerationError: Unable to generate pydantic-core schema for <class 'numpy.ndarray'>. Set `arbitrary_types_allowed=True` in the model_config to ignore this error or implement `__get_pydantic_core_schema__` on your type to fully support it.

ID: python/pydantic-arbitrary-type-not-allowed

其他格式: JSON · Markdown 中文 · English
80%修复率
89%置信度
0证据数
2024-07-14首次发现

版本兼容性

版本状态引入弃用备注
2.x active — — —

根因分析

字段使用了 Pydantic 无法验证的第三方类。Pydantic v2 对未知类型要求设置 arbitrary_types_allowed 或自定义核心模式。

English

A field uses a third-party class that Pydantic does not know how to validate. Pydantic v2 requires either arbitrary_types_allowed or a custom core schema for unknown types.

generic

解决方案

  1. 90% 成功率
    from pydantic import BaseModel, ConfigDict
    import numpy as np
    
    class Model(BaseModel):
        model_config = ConfigDict(arbitrary_types_allowed=True)
        arr: np.ndarray
  2. 88% 成功率
    from pydantic import field_serializer
    
    class Model(BaseModel):
        arr: np.ndarray
    
        @field_serializer('arr')
        def ser(self, v):
            return v.tolist()

无效尝试

常见但无效的做法:

  1. 85% 失败

    Pydantic still cannot build a schema for it; the error reappears at class definition or import time.

  2. 60% 失败

    Disables all validation and serialization for that field, losing type safety and JSON output.