sv-tools/marshmallow-objects

unknown=INCLUDE is currently broken

Closed this issue · 3 comments

Hello,

Looks like specifying unknown fields to be included (per marshmallow convention) is not compatible with marshmallow-objects.

Steps to reproduce:

>>> from marshmallow_objects import Model, INCLUDE, fields
>>> class T(Model):
...     class Meta:
...         unknown = INCLUDE
...
...     test = fields.Str()
...
>>> t = T(**{"test": "test string", "not_modeled": 1})
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-4-f034153db14f> in <module>
----> 1 t = T(**{"test": "test string", "not_modeled": 1})

...marshmallow_objects/models.py in __call__(cls, *args, **kwargs)
     75             for name, value in kwargs.items():
     76                 setattr(obj, name, value)
---> 77                 missing_fields.remove(name)
     78             obj.__missing_fields__ = missing_fields
     79             obj.__setattr_func__ = obj.__setattr_missing_fields__

KeyError: 'not_modeled'

Looks like the issue is in the missing_fields handling logic, it does not account for the Meta.unknown attribute.

This is not an ideal fix, but rather as a proof of concept I made the following change to line 77 in models.py:

   77                 try:
   78                     missing_fields.remove(name)
   79                 except KeyError as e:
   80                     if not obj.__schema__.Meta.unknown == 'include':
   81                         raise e

Then it works as expected:

>>> from marshmallow_objects import Model, INCLUDE, fields
>>> class T(Model):
...     class Meta:
...         unknown = INCLUDE
...
...     test = fields.Str()
...
>>> t = T(**{"test": "test string", "not_modeled": 1})
>>> t
T(**{'test': 'test string'})
>>> t.not_modeled
1

Thanks, will see

Should be fixed by #68
Released in v2.0.0: https://pypi.org/project/marshmallow-objects/2.0.0/

Hey, this issue seems like still exists, above example still fails if we use unknown = INCLUDE. Is there any plan to fix this?