lovasoa / marshmallow_dataclass

Automatic generation of marshmallow schemas from dataclasses.
https://lovasoa.github.io/marshmallow_dataclass/html/marshmallow_dataclass.html
MIT License
458 stars 78 forks source link

Do not create a default metadata["description"] #146

Open mjpieters opened 3 years ago

mjpieters commented 3 years ago

The metadata["description"] field is used when using the apispec project to generate OpenAPI specifications. Marshmallow_dataclass sets this field to the type name when using NewType and that clashes, as I don't need nor want to give every field a description in the spec.

Can we please decide for ourselves if description should be set?

mjpieters commented 3 years ago

I currently use this workaround, a class decorator I place above @marshmallow_dataclasses.dataclass:

from typing import TypeVar

T = TypeVar("T")

# slight annoyance: marshmallow-dataclasses sets a default `metadata["description"]`
# value. This class decorator removes descriptions set to None, and I set
# description: None on NewType fields to prevent the default values being set.
def _no_default_description(cls: T, _sentinel=object()) -> T:
    for field in cls.Schema._declared_fields.values():
        if field.metadata.get("description", _sentinel) is None:
            del field.metadata["description"]
    return cls

e.g.

from marshmallow_dataclass import NewType, dataclass

CustomType = NewType(
    "CustomType", BaseType, field=CustomField, metadata={"description": None}
)

@_no_default_description
@dataclass
class SomeSchema:
    some_field: CustomType