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 accessing builtin dict's attrs for a missing field #1557

Open
wants to merge 1 commit into
base: dev
Choose a base branch
from
Open
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 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>`_
mahenzon marked this conversation as resolved.
Show resolved Hide resolved
- 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:
mahenzon marked this conversation as resolved.
Show resolved Hide resolved
return default
return getattr(obj, key, default)


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