Skip to content

Commit

Permalink
Fix accessing builtin dict's attrs for a missing field
Browse files Browse the repository at this point in the history
  • Loading branch information
mahenzon committed Apr 5, 2020
1 parent e63158e commit fa24661
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 2 deletions.
2 changes: 1 addition & 1 deletion AUTHORS.rst
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ Contributors (chronological)
- Harlov Nikita `@harlov <https://github.com/harlov>`_
- `@stj <https://github.com/stj>`_
- Tomasz Magulski `@magul <https://github.com/magul>`_
- Suren Khorenyan `@surik00 <https://github.com/surik00>`_
- Suren Khorenyan `@mahenzon <https://github.com/mahenzon>`_
- Jeffrey Berger `@JeffBerger <https://github.com/JeffBerger>`_
- Felix Yan `@felixonmars <https://github.com/felixonmars>`_
- Prasanjit Prakash `@ikilledthecat <https://github.com/ikilledthecat>`_
Expand Down
4 changes: 3 additions & 1 deletion src/marshmallow/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)


Expand Down
18 changes: 18 additions & 0 deletions tests/test_serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -800,3 +800,21 @@ 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
: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}

0 comments on commit fa24661

Please sign in to comment.