Skip to content

Default deserialization with Function field #1819

Open
@CausticYarn

Description

@CausticYarn

Based on the documentation for the deserialize parameter for fields.Function:

  • deserialize – A callable from which to retrieve the value. The function must take a single argument value which is the value to be deserialized. It can also optionally take a context argument, which is a dictionary of context variables passed to the deserializer. If no callable is provided then value will be passed through unchanged.

I would expect that leaving the parameter out would populate the field with the source value, and that this code would work:

import marshmallow
from marshmallow import Schema, fields


class Bar(Schema):
    baz = fields.String()
    qux = fields.String()


class Foo(Schema):
    baz = fields.Function(serialize=lambda x: x['bar']['baz'])
    qux = fields.Function(serialize=lambda x: x['bar']['baz'])

    @marshmallow.post_load
    def post_load(self, data, many, **kwargs):
        return {'bar': data}


s = {'baz': 'blue', 'qux': 'orange'}

print(s)
d = Foo().load(s)

print(d)
print(Foo().dumps(d))

However, I get the error:

marshmallow.exceptions.ValidationError: {'baz': ['Unknown field.'], 'qux': ['Unknown field.']}

It works as I would expect if I do

class Foo(Schema):
    baz = fields.Function(serialize=lambda x: x['bar']['baz'],
                          deserialize=lambda x: x)
    qux = fields.Function(serialize=lambda x: x['bar']['baz'],
                          deserialize=lambda x: x)

Am I just reading the documentation wrong, or is this a bug?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions