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

Marshmallow hooks on schema inheritance #2031

Closed
codectl opened this issue Aug 7, 2022 · 1 comment
Closed

Marshmallow hooks on schema inheritance #2031

codectl opened this issue Aug 7, 2022 · 1 comment
Labels

Comments

@codectl
Copy link

codectl commented Aug 7, 2022

How can we chain Marshmallow hooks when you use schema inheritance?

Suppose the following "dumb" example:

from marshmallow import Schema, fields, post_load


class PersonSchema(Schema):
    name = fields.Str()

    @post_load
    def post_load(self, data, **_):
        data["name"] = data["name"].capitalize()
        return data


class EmployeeSchema(PersonSchema):
    title = fields.Str()

    @post_load
    def post_load(self, data, **_):
        data["title"] = data["title"].upper()
        return data

EmployeeSchema().load({"name": "john", "title": "ceo"})
# {"name": "john", "title": "CEO"}

In this example, only the subclassed hook was triggered. How do you make the parent hook trigger as well on deserialization, in this case?

@lafrech
Copy link
Member

lafrech commented Aug 9, 2022

This is not specific to marshmallow, but a Python issue. The child class overrides post_load method. Give it another name.

class PersonSchema(Schema):
    name = fields.Str()

    @post_load
    def capitalize(self, data, **_):
        data["name"] = data["name"].capitalize()
        return data


class EmployeeSchema(PersonSchema):
    title = fields.Str()

    @post_load
    def upper(self, data, **_):
        data["title"] = data["title"].upper()
        return data

Note the order is not guaranteed (#600).

@codectl codectl closed this as completed Aug 9, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants