datamodel-code-generator icon indicating copy to clipboard operation
datamodel-code-generator copied to clipboard

typename__ Field does not honor the `--use-default-kwarg` flag.

Open rpmcginty opened this issue 5 months ago • 0 comments

First off, thanks for making an awesome and easy to use tool!

Describe the bug

I use this tool to generate pydantic v2 models from graphql code. I am using the --use-default-kwarg flag to ensure that pydantic fields specify default as a keyword argument (mainly to comply with some silly pylance type hint issues otherwise).

when using this flag, I find that while all defined fields of a given class do comply with this configuration, the always present typename__ does not comply.

To Reproduce

Example schema:

tmp.bug.graphql

type TestType {
  "This is an ID field that is not required."
  typeId: String!
  "This is a description field that is optional."
  typeDescription: String
}
# generated by datamodel-codegen:
#   filename:  tmp.bug.graphql
#   timestamp: 2025-06-13T00:16:39+00:00

from __future__ import annotations

from typing import Literal, Optional, TypeAlias

from pydantic import BaseModel, Field

Boolean: TypeAlias = bool
"""
The `Boolean` scalar type represents `true` or `false`.
"""


String: TypeAlias = str
"""
The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text.
"""


class TestType(BaseModel):
    type_description: Optional[String] = Field(
        default=None,
        alias='typeDescription',
        description='This is a description field that is optional.',
    )
    type_id: String = Field(
        ..., alias='typeId', description='This is an ID field that is not required.'
    )
    typename__: Optional[Literal['TestType']] = Field('TestType', alias='__typename')

command that was used:

datamodel-codegen \
    --input tmp.bug.graphql  \
    --input-file-type graphql \
    --output-model-type pydantic_v2.BaseModel \
    --output tmp_bug.py \
    --target-python-version 3.11 \
    --use-schema-description \
    --snake-case-field \
    --use-default-kwarg

Expected behavior

I would have expected the typename__ field to also specify default using keyword argument.

class TestType(BaseModel):
    type_description: Optional[String] = Field(
        default=None,
        alias='typeDescription',
        description='This is a description field that is optional.',
    )
    type_id: String = Field(
        ..., alias='typeId', description='This is an ID field that is not required.'
    )
    typename__: Optional[Literal['TestType']] = Field(default='TestType', alias='__typename')

Version:

  • OS: macOS 15.4
  • Python version: 3.11
  • datamodel-code-generator version: 0.30.2

rpmcginty avatar Jun 13 '25 00:06 rpmcginty