Search code examples
pythonmarshmallow

Using input parameters for validation with marshmallow


Is it possible to pass parameters to a marshmallow schema to use for validation on load?

I have the following schema:

from marshmallow import Schema, fields, validate

class ExampleSchema(Schema):
    tags = fields.List(fields.String(), validate=ContainsOnly(["a", "b", "c"]))

and I'm wondering whether, instead of typing "a", "b", "c", I could put parameters in there? Something like

class ExampleSchema(Schema, list_of_allowed_tags):
    tags = fields.List(fields.String(), validate=ContainsOnly(list_of_allowed_tags))

except this doesn't work because the following error comes up on import

NameError: name 'list_of_allowed_tags' is not defined

Any other ideas?


Solution

  • No, marshmallow Schema doesn't do that.

    You can use a schema factory.

    import marshmallow as ma
    
    
    def example_schema_factory(list_of_allowed_tags):
    
        class ExampleSchema(ma.Schema):
            tags = ma.fields.List(
                ma.fields.String(),
                validate=ma.validate.ContainsOnly(list_of_allowed_tags)
            )
    
        return ExampleSchema