Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix nested schema context thread-safety #1833

Draft
wants to merge 1 commit into
base: dev
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/marshmallow/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -512,7 +512,7 @@ def schema(self):

if isinstance(nested, SchemaABC):
self._schema = copy.copy(nested)
self._schema.context.update(context)
self._schema.context = context
# Respect only and exclude passed from parent and re-initialize fields
set_class = self._schema.set_class
if self.only is not None:
Expand Down
19 changes: 19 additions & 0 deletions tests/test_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -2580,6 +2580,25 @@ class OuterSchema(Schema):
obj = {"inner": {"foo": 42}}
assert outer.dump(obj)

def test_context_thread_safe(self):
class InnerSchema(Schema):
i = fields.Integer()

class OuterSchema(Schema):
inner = fields.Nested(InnerSchema)

outer_1 = OuterSchema()
outer_1.context = {1: 1}
outer_1.dump({"inner": {"i": 1}})
outer_2 = OuterSchema()
outer_2.context = {2: 2}
outer_2.dump({"inner": {"i": 1}})

assert outer_1.context == {1: 1}
assert outer_2.context == {2: 2}
assert outer_1.fields["inner"].context == {1: 1}
assert outer_2.fields["inner"].context == {2: 2}


def test_serializer_can_specify_nested_object_as_attribute(blog):
class BlogUsernameSchema(Schema):
Expand Down