[Python] Ignore some default values in pydantic during JSON schema generation

Discussão em 'Python' iniciado por Stack, Julho 15, 2025.

  1. Stack

    Stack Membro Participativo

    (At the time of writing, this is on pydantic version 2.11.7) I have the following MRE:

    import json
    import time
    from pydantic import BaseModel, Field

    class SeededModel(BaseModel):
    seed: int = Field(default_factory=lambda _: int(time.time() * 1000))
    sensible_default: bool = False

    class Base(BaseModel):
    settings: SeededModel = SeededModel()

    config_schema = Base.model_json_schema()
    print(json.dumps(config_schema, indent=2))


    When I go to run this, I get the following JSON schema:

    {
    "$defs": {
    "SeededModel": {
    "properties": {
    "seed": {
    "title": "Seed",
    "type": "integer"
    },
    "sensible_default": {
    "default": false,
    "title": "Sensible Default",
    "type": "boolean"
    }
    },
    "title": "SeededModel",
    "type": "object"
    }
    },
    "properties": {
    "settings": {
    "$ref": "#/$defs/SeededModel",
    "default": {
    "seed": 1752596882987,
    "sensible_default": false
    }
    }
    },
    "title": "Base",
    "type": "object"
    }


    Is there a nice way to provide a default for Base#settings that preserves the default value for SeededModel#sensible_default but not for SeededModel#seed?

    Continue reading...

Compartilhe esta Página