python type_error ai_generated partial

pydantic.errors.PydanticInvalidForJsonSchema:无法为 core_schema.CallableSchema 生成 JsonSchema

pydantic.errors.PydanticInvalidForJsonSchema: Cannot generate a JsonSchema for core_schema.CallableSchema

ID: python/pydantic-json-schema-mode

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

版本兼容性

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

根因分析

字段类型为 Callable,无法映射到 JSON schema。调用 model_json_schema() 会抛错。

English

A field is typed as Callable, which has no JSON schema representation. Calling model_json_schema() raises.

generic

解决方案

  1. 80% 成功率
    from pydantic import BaseModel, Field
    from typing import Callable
    class M(BaseModel):
        model_config = {'json_schema_extra': {'examples': []}}
        handler: Callable = Field(exclude=True)
  2. 85% 成功率
    class M(BaseModel):
        handler_name: str  # resolved at runtime via registry

无效尝试

常见但无效的做法:

  1. 50% 失败

    Loses validation; JSON schema becomes empty object with no guidance.

  2. 60% 失败

    Breaks OpenAPI docs and client SDK generation for the whole app.

  3. 70% 失败

    Security risk and still no schema for the callable's shape.