Skip to content

msgspec.Struct discriminator tag is generated as None for single-value enum discriminator fields #3152

Description

@taebow

Describe the bug

When generating msgspec.Struct models from an OpenAPI discriminated union, a variant whose discriminator field is a single-value enum is generated with tag=None.

For example:

class StartedEvent(Struct, tag_field='type', tag=None):

I would expect the generated tag to use the discriminator enum value instead.

To Reproduce

openapi.yaml:

openapi: 3.1.0
info: {title: Repro, version: 0.0.1}
paths: {}
components:
  schemas:
    Event:
      discriminator: {propertyName: type}
      oneOf:
        - $ref: '#/components/schemas/StartedEvent'
        - $ref: '#/components/schemas/StoppedEvent'
    StartedEvent:
      type: object
      properties:
        type: {type: string, enum: [started]}
      required: [type]
    StoppedEvent:
      type: object
      properties:
        type: {type: string, enum: [stopped]}
      required: [type]

Run:

datamodel-codegen \
  --input openapi.yaml \
  --input-file-type openapi \
  --output-model-type msgspec.Struct \
  --output model.py \
  --target-python-version 3.10 \
  --enum-field-as-literal all \
  --use-one-literal-as-default \
  --disable-timestamp \
  --disable-warnings

Actual generated output:

class StartedEvent(Struct, tag_field='type', tag=None):
    pass


class StoppedEvent(Struct, tag_field='type', tag=None):
    pass

Expected generated output:

class StartedEvent(Struct, tag_field='type', tag='started'):
    pass


class StoppedEvent(Struct, tag_field='type', tag='stopped'):
    pass

Version

  • OS: Linux
  • Python version: 3.10.20
  • datamodel-code-generator version: 0.57.0
  • msgspec version: 0.21.1

Additional context

--use-one-literal-as-default does not fix this for msgspec.Struct.

This may be related to #2002, but the behavior here is specific to msgspec.Struct tag generation: the class kwarg is written as tag=None instead of the single discriminator enum value.

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