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

missing and default values should be specified in deserialized form #378

Closed
chadrik opened this Issue Jan 14, 2016 · 4 comments

Comments

Projects
None yet
5 participants
@chadrik

chadrik commented Jan 14, 2016

Marshmallow expects missing and default values to be specified in a pre-serialized form, which is inconvenient and unintuitive.

Here is a schema which I would expect to work:

import datetime
import uuid

class TestSchema(Schema):
    id = fields.UUID(
        missing=uuid.uuid1)
    ts = fields.DateTime(
        format='rfc',
        missing=datetime.datetime.now)

However, it does not:

schema = TestSchema()
pprint.pprint(tuple(schema.load({})))
({}, {'id': [u'Not a valid UUID.'], 'ts': [u'Not a valid datetime.']})

Instead, I have to convert my default and missing values to primitive types, which undermines the purpose of a library like marshmallow that already knows how to do this. For data types like datetimes, which have many possible serialized formats, I have to keep the formatting of my default and missing values in sync with my field properties, which is fragile and convoluted:

from email.Utils import formatdate

class TestSchema(Schema):
    id = fields.UUID(
        missing=lambda: str(uuid.uuid1()))
    ts = fields.DateTime(
        format='rfc',
        missing=formatdate)

In the case of default values, marshmallow does not attempt to validate them, so no error is raised, but the resulting document is not deserializable.

@immerrr

This comment has been minimized.

Contributor

immerrr commented Jan 20, 2016

I have hit this working with comma-delimited parameters in webargs.

@costrouc

This comment has been minimized.

costrouc commented Jan 5, 2017

I had this exact same error. I find it unintuitive that missing=datetime.now does not work but instead requires missing=lambda: str(datetime.now())

@sloria

This comment has been minimized.

Member

sloria commented Mar 21, 2017

I think the OP makes sense. I would gladly review and merge a PR for this.

@lafrech

This comment has been minimized.

Member

lafrech commented Mar 21, 2018

I just sent a PR to achieve this.

@chadrik, @costrouc, @sloria, feedback welcome.

lafrech added a commit to Nobatek/marshmallow that referenced this issue Mar 28, 2018

@sloria sloria closed this in #756 Mar 30, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment