Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support unknown=INCLUDE #279

Open
llucax opened this issue Dec 5, 2024 · 0 comments
Open

Add support unknown=INCLUDE #279

llucax opened this issue Dec 5, 2024 · 0 comments

Comments

@llucax
Copy link

llucax commented Dec 5, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant