Repository: marshmallow-code/marshmallow

Issue:
Error when unpickleable object in nested schema's context
> I have nested schema instance which context contains non-pickling object. In my case it is `Crypto.Cipher.AES` object which i tried to deepcopy in console and got an error. 

_Originally posted by @metheoryt in https://github.com/marshmallow-code/marshmallow/pull/1385_

Discussion:

Patch:
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index ccd53e4b..90db286b 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -8,6 +8,8 @@ Bug fixes:
 
 - Restore inheritance hierarchy of ``Number`` fields (:pr:`1403`).
   ``fields.Integer`` and ``fields.Decimal`` inherit from ``fields.Number``.
+- Fix bug that raised an uncaught error when a nested schema instance had an unpickleable object in its context (:issue:`1404`).
+  Thanks :user:`metheoryt` for reporting.
 
 3.1.0 (2019-09-15)
 ++++++++++++++++++
diff --git a/src/marshmallow/fields.py b/src/marshmallow/fields.py
index ad818a47..063581fe 100644
--- a/src/marshmallow/fields.py
+++ b/src/marshmallow/fields.py
@@ -506,7 +506,7 @@ class Nested(Field):
             # Inherit context from parent.
             context = getattr(self.parent, "context", {})
             if isinstance(self.nested, SchemaABC):
-                self._schema = copy.deepcopy(self.nested)
+                self._schema = copy.copy(self.nested)
                 self._schema.context.update(context)
                 # Respect only and exclude passed from parent and re-initialize fields
                 set_class = self._schema.set_class


Test patch:
diff --git a/tests/test_schema.py b/tests/test_schema.py
index 5cdbabc9..2be35b77 100644
--- a/tests/test_schema.py
+++ b/tests/test_schema.py
@@ -2428,6 +2428,22 @@ class TestContext:
         outer.context["foo_context"] = "foo"
         assert outer.load({"bars": {"test": {"foo": 42}}})
 
+    # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1404
+    def test_nested_field_with_unpicklable_object_in_context(self):
+        class Unpicklable:
+            def __deepcopy__(self, _):
+                raise NotImplementedError
+
+        class InnerSchema(Schema):
+            foo = fields.Field()
+
+        class OuterSchema(Schema):
+            inner = fields.Nested(InnerSchema(context={"unp": Unpicklable()}))
+
+        outer = OuterSchema()
+        obj = {"inner": {"foo": 42}}
+        assert outer.dump(obj)
+
 
 def test_serializer_can_specify_nested_object_as_attribute(blog):
     class BlogUsernameSchema(Schema):