Skip to content

--use-type-alias: inline object unions validate defaults through the first branch only #3035

@keyz

Description

@keyz

Describe the bug
datamodel-code-generator==0.54.1 generates an incorrect default_factory for inline object unions: it always validates through the first branch.

To Reproduce

Example schema:

{
  "$defs": {
    "A": { "properties": { "type": { "const": "a" } } },
    "B": { "properties": { "type": { "const": "b" } } }
  },
  "properties": {
    "x": {
      "default": { "type": "b" },
      "anyOf": [
        { "$ref": "#/$defs/A" },
        { "$ref": "#/$defs/B" }
      ]
    }
  }
}

Used commandline:

$ datamodel-codegen \
    --input schema.json \
    --input-file-type jsonschema \
    --output out.py \
    --output-model-type pydantic_v2.BaseModel \
    --use-type-alias \
    --target-python-version 3.12

Observed output:

class Model(BaseModel):
    x: A | B | None = Field(default_factory=lambda: A.model_validate({"type": "b"}))

Observed behavior:

  • mypy passes
  • Model() fails at runtime because {"type": "b"} is validated as A

Expected:

  • validate the default against the union and produce B, not hardcode branch 1

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions