Skip to content

Multiple schemas for same nested type in data class with marshmallow-dataclass > 8.5.3 #762

@DanielPettersson

Description

@DanielPettersson

When generating a schema for a single data class referencing same nested type in multiple fields each field get a separate schema. Even though it is the same type. Though, the trick is that this only happens if you first get the schema for the type in a different call context.

Code to reproduce the bug:

from dataclasses import dataclass

import marshmallow_dataclass
from apispec import APISpec
from apispec.ext.marshmallow import MarshmallowPlugin


@dataclass
class Foo:
    s: str

@dataclass
class Bar:
    a: Foo
    b: Foo


def get_marshmallow_schema():
    marshmallow_dataclass.class_schema(Bar)()

# When this function is called the bug is triggered. Commenting out this line makes the bug not happen.
get_marshmallow_schema()


spec = APISpec(
    title="Test schema",
    version="0.0.1",
    openapi_version="3.0.3",
    plugins=[MarshmallowPlugin()],
)

spec.components.schema("bar", schema=marshmallow_dataclass.class_schema(Bar))

print(spec.to_yaml())

Running the above code will output the warning from marshmallow plugin:
UserWarning: Multiple schemas resolved to the name Foo. The name has been modified. Either manually add each of the schemas with a different name or provide a custom schema_name_resolver.

And the schema for Bar will look like:

properties:
        a:
          $ref: '#/components/schemas/Foo1'
        b:
          $ref: '#/components/schemas/Foo'
      required:
      - a
      - b
      type: object

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions