marshmallow-code / marshmallow-code/marshmallow
dumping a dictionary with a schema containing an optional field 'items'
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 7.2k
- Forks
- 738
- Avg merge
- 1d 23h
- Merged PRs (30d)
- 7
Description
I'll start with a simple example
```python
from dataclasses import dataclass
from marshmallow import Schema, fields
class ListItem(Schema):
foo = fields.Str(required=True)
class MySchema(Schema):
bar = fields.Str(required=True)
items = fields.List(fields.Nested(ListItem()), required=True)
@dataclass
class Thing:
bar: str = None
thing = Thing(bar="barbarbar")
d = {"bar": "barbarbar"}
print(MySchema().dump(obj=thing)) # this works
print(MySchema().dump(obj=d)) # this gives an error "TypeError: 'builtin_function_or_method' object is not iterable"
```
The issue appears because on `utils.py`'s function `_get_value_for_key` it first tries to getattr, then obj[key] (without default), and finally getattr again, resulting in the `items` *method* for dict, rather than a default. This is extremely unexpected behaviour.
A workaround is to override `get_attribute` to try `.get` first on dictionaries.
```python
class MyBaseSchema(Schema):
def get_attribute(self, obj: Any, attr: str, default: Any):
"""Defines how to pull values from an object to serialize."""
if isinstance(obj, Dict):
return obj.get(attr, default)
return getattr(obj, attr, default)
```
I am not sure what the prefered fix in marshmallow would be given the rather dizzying levels of indirection and cases in the get attribute chain.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start in utils.py at _get_value_for_key and reproduce the issue with the MySchema and dictionary example from the report. Compare dictionary and dataclass dumping, including the missing items field and the get_attribute workaround. Done means dumping the dictionary does not treat the dict.items method as the field value and preserves the working dataclass behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- backend
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 42/100