I have a hierarchical definition of dataclasses for which I use marshmallow to serialize/deserialize them.
In certain dataclasses there are fields that should not be serialized which I can do using the class Meta, however, when then deserializing the the same object back it throws an exception.
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)
How can the serialized object be deserialzed with the excluded fields?