Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

    def partial(self):
        return Foo.schema().dump(self)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading