Skip to content

Add field-level pre/post-load API #2787

Open
0 of 1 issue completed
Open
Feature
0 of 1 issue completed
@sloria

Description

@sloria

As suggested by @lafrech in #2786 (review), we can enable pre/post-load on fields to address use cases like whitespace trimming (#1391) via an API similar to the schema-level pre/post_load/dump API.

Something like:

from marshmallow import Schema, fields

class ArtistSchema(Schema):
    name = fields.Str(post_load=(str.strip, str.upper))
    email = fields.Str(post_load=(str.strip, str.upper))
  • pro: allows field-specific transformations without having to implement a custom field
  • pro: non-breaking change
  • con: overlaps with existing functionality provided by custom fields and the schema-level @pre/post_load

Alternatives considered

Allow validators to transform values

Decorator API

update: this was considered as part of the original proposal but rejected/tabled (#2787 (comment) and #2787 (comment))

from marshmallow import Schema, fields, field_post_load

class ArtistSchema(Schema):
    name = fields.Str()
    email = fields.Str()

    @field_post_load("name", "email")
    def strip_whitespace(self, field_name: str, value: str) -> str:
        return value.strip()

Sub-issues

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions