Skip to content

post_load decorated functions with same name are not executed  #1439

@cimourdain

Description

@cimourdain

With schema inheritance or mixins, post_load decorators execution is dependant of their function name.

In the following example:

from marshmallow import Schema, fields, post_load


class Schema1(Schema):
    toto = fields.String()

    @post_load
    def schema1_post_load(self, data, **kwargs):
        print('Schema1 post load: data = %s' % data)
        return data


class Schema2(Schema):
    toto = fields.String()

    @post_load
    def schema2_post_load(self, data, **kwargs):
        print('Schema2 post load: data = %s' % data)
        return data


class MixinSchema(Schema2, Schema1):
    titi = fields.String()

    @post_load
    def mixinshchema_post_load(self, data, **kwargs):
        print('MixinSchema post load: data = %s' % data)
        return data


if __name__ == "__main__":
    payload = {
        'toto': 'gfdgefrh',
        'titi': 'fdghfgjhjh'
    }

    result = MixinSchema().load(payload)

This example produces the following output:

MixinSchema post load: data = {'titi': 'fdghfgjhjh', 'toto': 'gfdgefrh'}
Schema1 post load: data = {'titi': 'fdghfgjhjh', 'toto': 'gfdgefrh'}
Schema2 post load: data = {'titi': 'fdghfgjhjh', 'toto': 'gfdgefrh'}

As per the decorators documentation i understand that the execution order is not guaranteed, so the output is fine by me because all the post_loads are executed.

Then, when i give the MixinSchema post_load function the same name as Schema2:

from marshmallow import Schema, fields, post_load


class Schema1(Schema):
    toto = fields.String()

    @post_load
    def schema1_post_load(self, data, **kwargs):
        print('Schema1 post load: data = %s' % data)
        return data


class Schema2(Schema):
    toto = fields.String()

    @post_load
    def schema2_post_load(self, data, **kwargs):
        print('Schema2 post load: data = %s' % data)
        return data


class MixinSchema(Schema2, Schema1):
    titi = fields.String()

    @post_load
    def schema2_post_load(self, data, **kwargs):
        print('MixinSchema post load: data = %s' % data)
        return data


if __name__ == "__main__":
    payload = {
        'toto': 'gfdgefrh',
        'titi': 'fdghfgjhjh'
    }

    result = MixinSchema().load(payload)

Then i get the following output:

Schema1 post load: data = {'titi': 'fdghfgjhjh', 'toto': 'gfdgefrh'}
MixinSchema post load: data = {'titi': 'fdghfgjhjh', 'toto': 'gfdgefrh'}

The Schema2 post_load is not executed. From my point of view, post_load execution should not be dependant of function naming.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions