marshmallow icon indicating copy to clipboard operation
marshmallow copied to clipboard

Conveniently generating schema from a nested dict

Open archiif opened this issue 3 years ago • 2 comments

I'm trying to use marshmallow to validate configuration files and I would like to know how to conveniently generate nested schemas using a dictionary.

Right now, this is the only method I could think of:

def nest(obj):
    return fields.Nested(Schema.from_dict(obj))

defaults = {
    "path": nest(
        {
            "file": fields.Str(),
            "more_file": fields.Str(),
        }
    ),
    "cred": nest(
        {
            "user": fields.Str(),
            "pass": fields.Str(),
        }
    ),
}

config = json.load(config_path)
schema = Schema.from_dict(defaults)()
schema.load(config)

But it's very inconvenient. Is there a better method that I'm not aware of?

archiif avatar Mar 06 '21 17:03 archiif

See #1322.

It was not the initial intention when adding the from_dict feature. But it can still be discussed.

lafrech avatar Mar 06 '21 21:03 lafrech

I think this would be incredibly convenient to have. This is probably the best data validation library on Python that I have found so far, and this is the only one gripe I have with it. Would implementing this be difficult?

archiif avatar Mar 06 '21 22:03 archiif