Skip to content

Commit 94234ac

Browse files
authored
Handle post_load methods that append to data (#2797)
1 parent 0f073e6 commit 94234ac

File tree

3 files changed

+28
-1
lines changed

3 files changed

+28
-1
lines changed

CHANGELOG.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,9 @@ Bug fixes:
1414

1515
- Respect ``data_key`` when schema validators raise a `ValidationError <marshmallow.exceptions.ValidationError>`
1616
with a ``field_name`` argument (:issue:`2170`). Thanks :user:`matejsp` for reporting.
17+
- Correctly handle multiple `@post_load <marshmallow.post_load>` methods where one method appends to
18+
the data and another passes ``pass_original=True`` (:issue:`1755`).
19+
Thanks :user:`ghostwheel42` for reporting.
1720

1821
Documentation:
1922

src/marshmallow/schema.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
from abc import ABCMeta
1616
from collections import OrderedDict, defaultdict
1717
from collections.abc import Mapping
18+
from itertools import zip_longest
1819

1920
from marshmallow import base, class_registry, types
2021
from marshmallow import fields as ma_fields
@@ -1291,7 +1292,7 @@ def _invoke_processors(
12911292
if pass_original:
12921293
data = [
12931294
processor(item, original, many=many, **kwargs)
1294-
for item, original in zip(data, original_data)
1295+
for item, original in zip_longest(data, original_data)
12951296
]
12961297
else:
12971298
data = [processor(item, many=many, **kwargs) for item in data]

tests/test_decorators.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -925,3 +925,26 @@ class ExampleSchema(Schema):
925925

926926
schema = ExampleSchema()
927927
assert schema.load(data) == data
928+
929+
930+
# https://github.com/marshmallow-code/marshmallow/issues/1755
931+
def test_post_load_method_that_appends_to_data():
932+
class MySchema(Schema):
933+
foo = fields.Int()
934+
935+
@post_load(pass_many=True)
936+
def append_to_data(self, data, **kwargs):
937+
data.append({"foo": 42})
938+
return data
939+
940+
@post_load(pass_many=False, pass_original=True)
941+
def noop(self, data, original_data, **kwargs):
942+
if original_data is None: # added item
943+
assert data == {"foo": 42}
944+
else:
945+
assert original_data == {"foo": 24}
946+
assert data == {"foo": 24}
947+
return data
948+
949+
schema = MySchema(many=True)
950+
assert schema.load([{"foo": 24}]) == [{"foo": 24}, {"foo": 42}]

0 commit comments

Comments
 (0)