-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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