Skip to content

Fix Constant field with required=True raising ValueError#2910

Open
rstar327 wants to merge 1 commit intomarshmallow-code:devfrom
rstar327:fix-constant-required
Open

Fix Constant field with required=True raising ValueError#2910
rstar327 wants to merge 1 commit intomarshmallow-code:devfrom
rstar327:fix-constant-required

Conversation

@rstar327
Copy link

Fixes #2900

fields.Constant always sets load_default to the constant value internally. Since #2894 added a check that rejects load_default on required fields, Constant(constant, required=True) now raises ValueError.

This PR fixes the issue by:

  1. Extracting required from kwargs before calling super().__init__(), then setting it after
  2. Overriding _validate_missing in Constant to skip the required-field check, since the constant value is always available via load_default
# Before
fields.Constant("foo", required=True)
# ValueError: 'load_default' must not be set for required fields.

# After
class MySchema(Schema):
    type_ = fields.Constant("foo", required=True)

MySchema().load({})       # {'type_': 'foo'}
MySchema().dump({})       # {'type_': 'foo'}
MySchema().fields["type_"].required  # True

All 1133 tests pass.

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.

fields.Constant with required=True flag raised load_default warning

1 participant