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

Dataclasses with excluded fields don't round-trip #168

Open
svartkanin opened this issue Nov 22, 2021 · 0 comments
Open

Dataclasses with excluded fields don't round-trip #168

svartkanin opened this issue Nov 22, 2021 · 0 comments

Comments

@svartkanin
Copy link

I have a hierarchical structure of dataclasse that should be serialized and deserialzed. Some classes contain fields that should be ignored by both the serialization and deserialization process. When excluding them from the serialization it works fine but when then trying to deserialize them again it fails.

Here's an example of the problem

import uuid
import dataclasses
from dataclasses import dataclass, field
from typing import Tuple, List, Any
from marshmallow import Schema, EXCLUDE
from marshmallow_dataclass import class_schema


@dataclass(init=False)
class Base:
    id: uuid.UUID = field(default=None)

    class Meta:
        ordered = True
        additional = ['id']


    def __init__(self, **kwargs):
        fields = dataclasses.fields(self)
        names = set([f.name for f in fields])
        for k, v in kwargs.items():
            if k in names:
                setattr(self, k, v)

        if self.id is None:
            self.id = uuid.uuid4()


@dataclass(init=False)
class User(Base):
    name: str
    _options: List[Any] = field(default_factory=list)

    class Meta:
        unknown = EXCLUDE
        exclude = ['_options']

    @property
    def options(self) -> list:
        return self._options


@dataclass(init=False)
class Person(Base):
    location: str
    _address: List[Any] = field(default_factory=list)

    class Meta:
        unknown = EXCLUDE
        exclude = ['_address']


user = User()
user.name = 'test_user'

person = Person()
person.location = 'earth'


user_schema = class_schema(User)()
person_schema = class_schema(Person)()

serialized_user = user_schema.dump(user)
serialized_person = person_schema.dump(person)

print(serialized_user)
print(serialized_person)

deserialized_user = user_schema.load(serialized_user)
print(deserialized_user)

Maybe I'm not using the right Meta tags for it, could you share if there's others that should be used in this specific case?

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