Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Marshmallow Field can be two different types

I want to specify a marshmallow schema. For one of my fields, I want it to be validated however it can be EITHER a string or a list of strings. I have tried the Raw field type however that is allows everything through. Is there a way to just validate the two types that I want?

Something like,

value = fields.Str() or fields.List()
like image 528
Jimmy Jo Avatar asked Jun 08 '26 00:06

Jimmy Jo


1 Answers

I had the same issue today, and I came up with this solution:

class ValueField(fields.Field):
    def _deserialize(self, value, attr, data, **kwargs):
        if isinstance(value, str) or isinstance(value, list):
            return value
        else:
            raise ValidationError('Field should be str or list')


class Foo(Schema):
    value = ValueField()
    other_field = fields.Integer()

You can create a custom field and overload the _deserialize method so that it validates if the code isinstance of desired types. I hope it'll work for you.

foo.load({'value': 'asdf', 'other_field': 1})
>>> {'other_field': 1, 'value': 'asdf'}
foo.load({'value': ['asdf'], 'other_field': 1})
>>> {'other_field': 1, 'value': ['asdf']}
foo.load({'value': 1, 'other_field': 1})
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/Users/webinterpret/Envs/gl-gs-onboarding-api/lib/python3.7/site-packages/marshmallow/schema.py", line 723, in load
    data, many=many, partial=partial, unknown=unknown, postprocess=True
  File "/Users/webinterpret/Envs/gl-gs-onboarding-api/lib/python3.7/site-packages/marshmallow/schema.py", line 904, in _do_load
    raise exc
marshmallow.exceptions.ValidationError: {'value': ['Field should be str or list']}
like image 68
Piotr BG Avatar answered Jun 10 '26 14:06

Piotr BG