From 92d6d95b31da24aa58c268fc01313917e1c138a2 Mon Sep 17 00:00:00 2001 From: nyxst4ck <289980115+nyxst4ck@users.noreply.github.com> Date: Mon, 29 Jun 2026 22:46:38 -0300 Subject: [PATCH] fix(schema): handle collection pre-load before validators --- AUTHORS.rst | 1 + src/marshmallow/schema.py | 7 +++++-- tests/test_decorators.py | 16 ++++++++++++++++ 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/AUTHORS.rst b/AUTHORS.rst index cd928bdf9..16196f377 100644 --- a/AUTHORS.rst +++ b/AUTHORS.rst @@ -188,3 +188,4 @@ Contributors (chronological) - `@rstar327 `_ - Kadir Can Ozden `@bysiber `_ - Dhruvil Darji `@dhruvildarji `_ +- `@nyxst4ck `_ diff --git a/src/marshmallow/schema.py b/src/marshmallow/schema.py index 8024dfe13..2c4172e7d 100644 --- a/src/marshmallow/schema.py +++ b/src/marshmallow/schema.py @@ -1192,9 +1192,12 @@ def _invoke_schema_validators( pass_original = validator_kwargs.get("pass_original", False) if many and not pass_collection: - for idx, (item, orig) in enumerate( + data_items = ( zip(data, original_data, strict=True) - ): + if pass_original + else ((item, None) for item in data) + ) + for idx, (item, orig) in enumerate(data_items): self._run_validator( validator, item, diff --git a/tests/test_decorators.py b/tests/test_decorators.py index fce7e442b..b6efd6343 100644 --- a/tests/test_decorators.py +++ b/tests/test_decorators.py @@ -619,6 +619,22 @@ def check(datum): errors = schema.validate([{"foo": 4, "bar": "42"}], many=True) assert errors["_schema"] == ["bar cannot be a string"] + def test_collection_pre_load_can_change_length_before_item_schema_validation(self): + class MySchema(Schema): + foo = fields.Int() + + @pre_load(pass_collection=True) + def remove_items_without_foo(self, data, **kwargs): + return [item for item in data if item.get("foo") != ""] + + @validates_schema + def validate_foo(self, data, **kwargs): + assert "foo" in data + + schema = MySchema() + + assert schema.load([{"foo": 24}, {"foo": ""}], many=True) == [{"foo": 24}] + def test_allow_reporting_field_errors_in_schema_validator(self): class NestedSchema(Schema): baz = fields.Int(required=True)