Marshmallow: Method hooks swallow AttributeError

Created on 17 Feb 2016  路  5Comments  路  Source: marshmallow-code/marshmallow

If AttributeError is raised by a Method/Function hook, it is silently swallowed:

class C(Schema):
    f = fields.Method('_bad_serialize')
    def _bad_serialize(self, obj):
        return self._do_something_else(obj)  # raises AttributeError

test_type = namedtuple('test_type', 'f')
C(strict=True).dump(test_type(123))  # returns empty list

This makes finding the bugs harder. I understand the rationale and I guess fixing it might make some code backward incompatible, but is there a way to add at least some warning mode?

Most helpful comment

I intend to look into solutions for this in marshmallow 3.0

All 5 comments

This is super annoying... and should at least come with a way to switch off this behaviour for debugging purposes.

I intend to look into solutions for this in marshmallow 3.0

I don't understand the original reasons for writing it this way, except that attribute-based field types are omitted if the attribute is missing. Options might be:

  • add validation to serialization, and provide a built-in 'value exists' validator that can be easily used
  • add a new flag that tells the class not to squash the error

As mentioned in #582 :

Yes, the AttributeError is a wart from marshmallow's early days that accidentally made it into 2.0. I'm leaning towards removing the exception handling in marshmallow 3.0 and cutting an early release.

If there's interest in getting this fixed in 2.0, I can look into merging #582, but I'd rather users just upgrade to 3.0.

Was this page helpful?
0 / 5 - 0 ratings