Skip to content

--use-type-alias emits raw dict defaults for $ref object unions #3034

@keyz

Description

@keyz

Describe the bug
datamodel-code-generator==0.54.1 emits an invalid default for a $ref to an object union when --use-type-alias is enabled

To Reproduce

Example schema:

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

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:

type U = A | B

class Model(BaseModel):
    x: U | None = {"type": "b"}

Observed behavior:

  • mypy reports the default as incompatible
  • Model().x is a raw dict at runtime, not A | B

Expected:

  • emit a validated model default, not a raw dict literal

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions