diff --git a/AUTHORS.rst b/AUTHORS.rst index 6cae56ccc..29c56eb1c 100644 --- a/AUTHORS.rst +++ b/AUTHORS.rst @@ -99,7 +99,7 @@ Contributors (chronological) - Harlov Nikita `@harlov `_ - `@stj `_ - Tomasz Magulski `@magul `_ -- Suren Khorenyan `@surik00 `_ +- Suren Khorenyan `@mahenzon `_ - Jeffrey Berger `@JeffBerger `_ - Felix Yan `@felixonmars `_ - Prasanjit Prakash `@ikilledthecat `_ diff --git a/src/marshmallow/utils.py b/src/marshmallow/utils.py index f7782ac59..5b076814b 100644 --- a/src/marshmallow/utils.py +++ b/src/marshmallow/utils.py @@ -242,7 +242,9 @@ def _get_value_for_key(obj, key, default): try: return obj[key] - except (KeyError, IndexError, TypeError, AttributeError): + except (KeyError, IndexError, TypeError, AttributeError) as e: + if isinstance(e, KeyError) and type(obj) is dict: + return default return getattr(obj, key, default) diff --git a/tests/test_serialization.py b/tests/test_serialization.py index 7a25bd73c..7b72ef990 100644 --- a/tests/test_serialization.py +++ b/tests/test_serialization.py @@ -800,3 +800,23 @@ def gen(): data = OtherSchema().dump(obj) assert data.get("objects") == [{"name": "foo"}, {"name": "bar"}] + + +def test_missing_update_field_in_dict_processed_properly(): + """ + Checking case when a schema has 'update' field + and the object to be dumped is a dict + and the value for this field is missing + + https://github.com/marshmallow-code/marshmallow/pull/1557 + :return: + """ + + class MySchema(Schema): + update = fields.Boolean(required=False) + + schema = MySchema() + data = schema.dump({}) + assert data == {} + data = schema.dump({"update": True}) + assert data == {"update": True}