python type_error ai_generated true

pydantic.errors.PydanticSchemaGenerationError: Unable to generate pydantic-core schema for <class 'decimal.Decimal'>. 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-types-schema

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2024-04-09First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2.x active

Root Cause

A field uses a type (custom class, Decimal subclass, numpy dtype) that has no built-in pydantic-core schema.

generic

中文

字段使用了没有内置 pydantic-core schema 的类型(自定义类、Decimal 子类、numpy dtype 等)。

Workarounds

  1. 88% success
    from pydantic import BaseModel, ConfigDict
    class M(BaseModel):
        model_config = ConfigDict(arbitrary_types_allowed=True)
        amount: Decimal
  2. 82% success
    from typing import Annotated
    from pydantic import BaseModel, PlainSerializer
    from decimal import Decimal
    Amt = Annotated[Decimal, PlainSerializer(lambda d: str(d), return_type=str)]
    class M(BaseModel):
        amount: Amt

Dead Ends

Common approaches that don't work:

  1. 50% fail

    Disables validation and serialization; JSON schema loses type info.

  2. 60% fail

    Loses type guarantees; callers must re-parse everywhere.

  3. 75% fail

    Breaks all other models and is not supported across pydantic minor versions.