Skip to content

Commit 4661e9a

Browse files
committed
Fix accessing builtin dict's attrs for a missing field
1 parent e63158e commit 4661e9a

File tree

3 files changed

+24
-2
lines changed

3 files changed

+24
-2
lines changed

AUTHORS.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ Contributors (chronological)
9999
- Harlov Nikita `@harlov <https://github.com/harlov>`_
100100
- `@stj <https://github.com/stj>`_
101101
- Tomasz Magulski `@magul <https://github.com/magul>`_
102-
- Suren Khorenyan `@surik00 <https://github.com/surik00>`_
102+
- Suren Khorenyan `@mahenzon <https://github.com/mahenzon>`_
103103
- Jeffrey Berger `@JeffBerger <https://github.com/JeffBerger>`_
104104
- Felix Yan `@felixonmars <https://github.com/felixonmars>`_
105105
- Prasanjit Prakash `@ikilledthecat <https://github.com/ikilledthecat>`_

src/marshmallow/utils.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -242,7 +242,9 @@ def _get_value_for_key(obj, key, default):
242242

243243
try:
244244
return obj[key]
245-
except (KeyError, IndexError, TypeError, AttributeError):
245+
except (KeyError, IndexError, TypeError, AttributeError) as e:
246+
if isinstance(e, KeyError) and type(obj) is dict:
247+
return default
246248
return getattr(obj, key, default)
247249

248250

tests/test_serialization.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -800,3 +800,23 @@ def gen():
800800
data = OtherSchema().dump(obj)
801801

802802
assert data.get("objects") == [{"name": "foo"}, {"name": "bar"}]
803+
804+
805+
def test_missing_update_field_in_dict_processed_properly():
806+
"""
807+
Checking case when a schema has 'update' field
808+
and the object to be dumped is a dict
809+
and the value for this field is missing
810+
811+
https://github.com/marshmallow-code/marshmallow/pull/1557
812+
:return:
813+
"""
814+
815+
class MySchema(Schema):
816+
update = fields.Boolean(required=False)
817+
818+
schema = MySchema()
819+
data = schema.dump({})
820+
assert data == {}
821+
data = schema.dump({"update": True})
822+
assert data == {"update": True}

0 commit comments

Comments
 (0)