How can I restrict this dataclass serialization to only attributes on the base class?

Question:

Here’s some code:

from dataclasses import dataclass
from dataclasses_json import dataclass_json

@dataclass_json
@dataclass
class Foo:
    f: str

@dataclass_json
@dataclass
class Baz(Foo):
    b: str

    def full(self):
        return self.to_dict()
        # as expected, returns {"f":"f", "b":"b"}


    def partial(self):
        return Foo.to_dict(self)
        # also returns {"f":"f", "b":"b"}
        # how can I make it just return {"f":"f"}?


print(Baz(f="f", b="b").partial())

output:

{"f":"f"}

How can I restrict the value returned by partial to only f and not both b and f?

Answers:

You can use the Foo classes schema to only output fields that exist on Foo

    def partial(self):
        return Foo.schema().dump(self)
Answered By: Iain Shelvington
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.