marshmallow_dataclass icon indicating copy to clipboard operation
marshmallow_dataclass copied to clipboard

Add support `unknown=INCLUDE`

Open llucax opened this issue 1 year ago • 0 comments

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.

llucax avatar Dec 05 '24 10:12 llucax