Skip to content

Commit 19ca8dc

Browse files
Fix Constant field rejecting None values during load (#2894)
* Fix Constant field rejecting None values during load Signed-off-by: Emmanuel Ferdman <emmanuelferdman@gmail.com> * Update changelog and AUTHORS --------- Signed-off-by: Emmanuel Ferdman <emmanuelferdman@gmail.com> Co-authored-by: Steven Loria <git@stevenloria.com>
1 parent 213ee3a commit 19ca8dc

File tree

4 files changed

+20
-2
lines changed

4 files changed

+20
-2
lines changed

AUTHORS.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,3 +183,4 @@ Contributors (chronological)
183183
- Xiao `@T90REAL <https://github.com/T90REAL>`_
184184
- jfo `@jafournier <https://github.com/jafournier>`_
185185
- thanhlecongg `@thanhlecongg <https://github.com/thanhlecongg>`_
186+
- Emmanuel Ferdman `@emmanuel-ferdman <https://github.com/emmanuel-ferdman>`_

CHANGELOG.rst

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,14 @@
11
Changelog
22
=========
33

4+
unreleased
5+
----------
6+
7+
Bug fixes:
8+
9+
- Fix behavior of ``fields.Contant(None)`` (:issue:`2868`).
10+
Thanks :user:`T90REAL` for reporting and `emmanuel-ferdman` for the fix.
11+
412

513
4.2.1 (2026-01-23)
614
------------------

src/marshmallow/fields.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2065,10 +2065,10 @@ class Constant(Field[_ContantT]):
20652065
_CHECK_ATTRIBUTE = False
20662066

20672067
def __init__(self, constant: _ContantT, **kwargs: Unpack[_BaseFieldKwargs]):
2068+
kwargs["load_default"] = constant
2069+
kwargs["dump_default"] = constant
20682070
super().__init__(**kwargs)
20692071
self.constant = constant
2070-
self.load_default = constant
2071-
self.dump_default = constant
20722072

20732073
def _serialize(self, value, *args, **kwargs) -> _ContantT:
20742074
return self.constant

tests/test_deserialization.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1413,6 +1413,15 @@ class MySchema(Schema):
14131413
assert sch.load({})["foo"] == 42
14141414
assert sch.load({"foo": 24})["foo"] == 42
14151415

1416+
def test_constant_none_allows_none_value(self):
1417+
class MySchema(Schema):
1418+
foo = fields.Constant(None)
1419+
1420+
sch = MySchema()
1421+
assert sch.load({"foo": None})["foo"] is None
1422+
assert sch.load({})["foo"] is None
1423+
assert sch.load({"foo": "ignored"})["foo"] is None
1424+
14161425
def test_field_deserialization_with_user_validator_function(self):
14171426
field = fields.String(validate=predicate(lambda s: s.lower() == "valid"))
14181427
assert field.deserialize("Valid") == "Valid"

0 commit comments

Comments
 (0)