Skip to content

Allow passing a Field instance to unknown option#2911

Open
Br1an67 wants to merge 1 commit intomarshmallow-code:devfrom
Br1an67:feat/unknown-field-option
Open

Allow passing a Field instance to unknown option#2911
Br1an67 wants to merge 1 commit intomarshmallow-code:devfrom
Br1an67:feat/unknown-field-option

Conversation

@Br1an67
Copy link
Copy Markdown

@Br1an67 Br1an67 commented Mar 1, 2026

Summary

Allow a Field instance to be passed as the unknown option (in addition to the existing RAISE, INCLUDE, EXCLUDE constants). When a Field is provided, unknown field values are deserialized through that field, enabling validation and type coercion.

Closes #853

Example

from marshmallow import Schema, fields

class MySchema(Schema):
    name = fields.String()

schema = MySchema(unknown=fields.Int())
schema.load({"name": "Joe", "age": "42"})
# => {"name": "Joe", "age": 42}

The Field can be set via:

  • Schema(unknown=fields.Int())
  • class Meta: unknown = fields.Int()
  • schema.load(data, unknown=fields.Int())
  • fields.Nested(ChildSchema, unknown=fields.Int())

Changes

  • src/marshmallow/types.py: Updated UnknownOption type alias to include Field (under TYPE_CHECKING to avoid circular imports)
  • src/marshmallow/schema.py: Added isinstance(unknown, Field) branch in _deserialize that routes unknown values through the field's deserialize() method, with proper error collection
  • tests/test_schema.py: Added 7 tests covering: basic deserialization, validation errors, Meta config, many=True, load() kwarg, nested schemas, and passthrough with Field()

When `unknown` is set to a Field instance (e.g. `fields.Int()`),
unknown field values are deserialized through that field instead of
being included as-is. This enables validation and type coercion of
unknown fields.

The Field can be passed via Schema.__init__, class Meta, the `load()`
keyword argument, or Nested field's `unknown` parameter.

Closes marshmallow-code#853
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Allow specifying output field when using unknown=INCLUDE

1 participant