Dataclasses do not implement __iter__, causing webargs.use_kwargs to fail
See original GitHub issuewebargs will attempt to combine the results of schema.load into the resulting kwargs to be passed into a function, as seen here:
https://github.com/marshmallow-code/webargs/blob/5.5.1/src/webargs/core.py#L446-L448
In order to repair this assumption, while still using dataclasses, I had to implement a mixin for my dataclasses to allow them to appear as iterables for the purposes of kwargs.update(dataclass)
class Iterable:
def __iter__(self):
"""When extending a dataclass, yields all key value pairs as if it were a dictionary"""
for attr, value in self.__dict__.items():
if value is not None:
yield attr, value
@dataclass
class Building(Iterable):
# field metadata is used to instantiate the marshmallow field
height: float = field(metadata={"validate": marshmallow.validate.Range(min=0)})
name: str = field(default="anonymous")
Should I go make noise over in webargs saying they should accept dataclasses? or is this something that we can safely hack in here, as we’re are actively transforming the resulting dictionary INTO a dataclass.
Another acceptable solution would be to add a meta argument to allow a developer to skip the post_load
step, and allow load
to return a dictionary and NOT a dataclass, which is honestly more optimal IMO.
Issue Analytics
- State:
- Created 4 years ago
- Comments:5 (2 by maintainers)
Top GitHub Comments
It looks fine for now!
It definitely wasn’t on my radar to move away from
use_kwargs
but I can’t come up with anything that would be break this yet. I guess you’ll hear from me if there’s an issue.That should already work. @CptSpaceToaster can you try that out?