Skip to content

Instantly share code, notes, and snippets.

@jakebrinkmann
Forked from je55ek/immutable_json.py
Created January 13, 2020 19:47
Show Gist options
  • Save jakebrinkmann/f57f66c0feb60fe6248198246c8da475 to your computer and use it in GitHub Desktop.
Save jakebrinkmann/f57f66c0feb60fe6248198246c8da475 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