Skip to content

Instantly share code, notes, and snippets.

@je55ek
Created January 26, 2018 04:38
Show Gist options
  • Save je55ek/e97b138d87f37667a6b05c28decda013 to your computer and use it in GitHub Desktop.
Save je55ek/e97b138d87f37667a6b05c28decda013 to your computer and use it in GitHub Desktop.
Function to create an immutable data structure and its associated marshmallow schema in one fell swoop
from collections import namedtuple
from marshmallow import Schema
from marshmallow.decorators import post_load
def class_and_schema(class_name, fields):
"""Create a class and its marshmallow schema.
Example::
from marshmallow.fields import String, Integer
Person, PersonSchema = class_and_schema('Person', {
'name': String (required = True),
'age' : Integer(required = True)
})
"""
cls = namedtuple(name, fields.keys())
@post_load
def to_namedtuple(self, data):
return cls(**data)
schema = type(
name + 'Schema',
(Schema,),
{**fields, '_to_namedtuple': to_namedtuple}
)
return cls, schema
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment