Is it possible to pass parameters to a marshmallow schema to use for validation on load?
I have the following schema:
JavaScript
x
5
1
from marshmallow import Schema, fields, validate
2
3
class ExampleSchema(Schema):
4
tags = fields.List(fields.String(), validate=ContainsOnly(["a", "b", "c"]))
5
and I’m wondering whether, instead of typing "a", "b", "c"
, I could put parameters in there? Something like
JavaScript
1
3
1
class ExampleSchema(Schema, list_of_allowed_tags):
2
tags = fields.List(fields.String(), validate=ContainsOnly(list_of_allowed_tags))
3
except this doesn’t work because the following error comes up on import
JavaScript
1
2
1
NameError: name 'list_of_allowed_tags' is not defined
2
Any other ideas?
Advertisement
Answer
No, marshmallow Schema doesn’t do that.
You can use a schema factory.
JavaScript
1
13
13
1
import marshmallow as ma
2
3
4
def example_schema_factory(list_of_allowed_tags):
5
6
class ExampleSchema(ma.Schema):
7
tags = ma.fields.List(
8
ma.fields.String(),
9
validate=ma.validate.ContainsOnly(list_of_allowed_tags)
10
)
11
12
return ExampleSchema
13