Skip to content

Add support unknown=INCLUDE #279

@llucax

Description

@llucax

Hi, this is another attempt at #124.

We are using marshmallow_dataclass and it is great, but we would like to have a way to tell if some unknown fields were found in the data to warn users (it is very common to have typos in a config file for example).

Maybe a practical way to do this could be to declare a special field for this, like:

from typing import Any
from dataclasses import dataclass, field
from marshmallow_dataclass import class_schema

@dataclass
class Sample:
    id: int
    unknown_fields: dict[str, Any] | None = field(
        default=None, metadata={"metadata": {"stores_unknown_fields": True}}
    )

print(class_schema(Sample)().load({"id": "1"}))
# Sample(id=1, unknown_fields=None)
print(class_schema(Sample)().load({"id": "1", "oh-no": "hello"}, unknown=INCLUDE))
# Sample(id=1, unknown_fields={'oh-no': 'hello'})
print(class_schema(Sample)().load({"id": "1", "oh-no": "hello"}, unknown=EXCLUDE))
# Sample(id=1, unknown_fields=None)

If there are many fields with "stores_unknown_fields": True, they could be stored in all of them, or raise an exception.

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