• Stars
    star
    452
  • Rank 96,761 (Top 2 %)
  • Language
    Python
  • License
    MIT License
  • Created almost 6 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Automatic generation of marshmallow schemas from dataclasses.

marshmallow-dataclass

Test Workflow Status (master branch) PyPI version marshmallow 3 compatible download stats

Automatic generation of marshmallow schemas from dataclasses.

from dataclasses import dataclass, field
from typing import List, Optional

import marshmallow_dataclass
import marshmallow.validate


@dataclass
class Building:
    # field metadata is used to instantiate the marshmallow field
    height: float = field(metadata={"validate": marshmallow.validate.Range(min=0)})
    name: str = field(default="anonymous")


@dataclass
class City:
    name: Optional[str]
    buildings: List[Building] = field(default_factory=list)


city_schema = marshmallow_dataclass.class_schema(City)()

city = city_schema.load(
    {"name": "Paris", "buildings": [{"name": "Eiffel Tower", "height": 324}]}
)
# => City(name='Paris', buildings=[Building(height=324.0, name='Eiffel Tower')])

city_dict = city_schema.dump(city)
# => {'name': 'Paris', 'buildings': [{'name': 'Eiffel Tower', 'height': 324.0}]}

Why

Using schemas in Python often means having both a class to represent your data and a class to represent its schema, which results in duplicated code that could fall out of sync. As of Python 3.6, types can be defined for class members, which allows libraries to generate schemas automatically.

Therefore, you can document your APIs in a way that allows you to statically check that the code matches the documentation.

Installation

This package is hosted on PyPI.

pip3 install marshmallow-dataclass

You may optionally install the following extras:

pip3 install "marshmallow-dataclass[enum,union]"

marshmallow 2 support

marshmallow-dataclass no longer supports marshmallow 2. Install marshmallow_dataclass<6.0 if you need marshmallow 2 compatibility.

Usage

Use the class_schema function to generate a marshmallow Schema class from a dataclass.

from dataclasses import dataclass
from datetime import date

import marshmallow_dataclass


@dataclass
class Person:
    name: str
    birth: date


PersonSchema = marshmallow_dataclass.class_schema(Person)

The type of your fields must be either basic types supported by marshmallow (such as float, str, bytes, datetime, ...), Union, or other dataclasses.

Union (de)serialization coercion

Typically the Union type; Union[X, Y] means—from a set theory perspective—either X or Y, i.e., an unordered set, howevever the order of the sub-types defines the precedence when attempting to ether deserialize or serialize the value per here.

For example,

from typing import Union

from dataclasses import dataclass


@dataclass
class Person:
    name: str
    age: Union[int, float]


PersonSchema = marshmallow_dataclass.class_schema(Person)
PersonSchema().load({"name": "jane", "age": 50.0})
# => Person(name="jane", age=50)

will first (sucessfully) try to coerce 50.0 to an int. If coercion is not desired the Any type can be used with the caveat that values will not be type checked without additional validation.

Customizing generated fields

To pass arguments to the generated marshmallow fields (e.g., validate, load_only, dump_only, etc.), pass them to the metadata argument of the field function.

Note that starting with version 4, marshmallow will disallow passing arbitrary arguments, so any additional metadata should itself be put in its own metadata dict:

from dataclasses import dataclass, field
import marshmallow_dataclass
import marshmallow.validate


@dataclass
class Person:
    name: str = field(
        metadata=dict(
            load_only=True, metadata=dict(description="The person's first name")
        )
    )
    height: float = field(metadata=dict(validate=marshmallow.validate.Range(min=0)))


PersonSchema = marshmallow_dataclass.class_schema(Person)

@dataclass shortcut

marshmallow_dataclass provides a @dataclass decorator that behaves like the standard library's @dataclasses.dataclass and adds a Schema attribute with the generated marshmallow Schema.

# Use marshmallow_dataclass's @dataclass shortcut
from marshmallow_dataclass import dataclass


@dataclass
class Point:
    x: float
    y: float


Point.Schema().dump(Point(4, 2))
# => {'x': 4, 'y': 2}

Note: Since the .Schema property is added dynamically, it can confuse type checkers. To avoid that, you can declare Schema as a ClassVar.

from typing import ClassVar, Type

from marshmallow_dataclass import dataclass
from marshmallow import Schema


@dataclass
class Point:
    x: float
    y: float
    Schema: ClassVar[Type[Schema]] = Schema

Customizing the base Schema

It is also possible to derive all schemas from your own base Schema class (see marshmallow's documentation about extending Schema). This allows you to implement custom (de)serialization behavior, for instance specifying a custom mapping between your classes and marshmallow fields, or renaming fields on serialization.

Custom mapping between classes and fields

class BaseSchema(marshmallow.Schema):
    TYPE_MAPPING = {CustomType: CustomField, List: CustomListField}


class Sample:
    my_custom: CustomType
    my_custom_list: List[int]


SampleSchema = marshmallow_dataclass.class_schema(Sample, base_schema=BaseSchema)
# SampleSchema now serializes my_custom using the CustomField marshmallow field
# and serializes my_custom_list using the CustomListField marshmallow field

Renaming fields on serialization

import marshmallow
import marshmallow_dataclass


class UppercaseSchema(marshmallow.Schema):
    """A Schema that marshals data with uppercased keys."""

    def on_bind_field(self, field_name, field_obj):
        field_obj.data_key = (field_obj.data_key or field_name).upper()


class Sample:
    my_text: str
    my_int: int


SampleSchema = marshmallow_dataclass.class_schema(Sample, base_schema=UppercaseSchema)

SampleSchema().dump(Sample(my_text="warm words", my_int=1))
# -> {"MY_TEXT": "warm words", "MY_INT": 1}

You can also pass base_schema to marshmallow_dataclass.dataclass.

@marshmallow_dataclass.dataclass(base_schema=UppercaseSchema)
class Sample:
    my_text: str
    my_int: int

See marshmallow's documentation about extending Schema.

Custom NewType declarations

This library exports a NewType function to create types that generate customized marshmallow fields.

Keyword arguments to NewType are passed to the marshmallow field constructor.

import marshmallow.validate
from marshmallow_dataclass import NewType

IPv4 = NewType(
    "IPv4", str, validate=marshmallow.validate.Regexp(r"^([0-9]{1,3}\\.){3}[0-9]{1,3}$")
)

You can also pass a marshmallow field to NewType.

import marshmallow
from marshmallow_dataclass import NewType

Email = NewType("Email", str, field=marshmallow.fields.Email)

For convenience, some custom types are provided:

from marshmallow_dataclass.typing import Email, Url

Note: if you are using mypy, you will notice that mypy throws an error if a variable defined with NewType is used in a type annotation. To resolve this, add the marshmallow_dataclass.mypy plugin to your mypy configuration, e.g.:

[mypy]
plugins = marshmallow_dataclass.mypy
# ...

Meta options

Meta options are set the same way as a marshmallow Schema.

from marshmallow_dataclass import dataclass


@dataclass
class Point:
    x: float
    y: float

    class Meta:
        ordered = True

Documentation

The project documentation is hosted on GitHub Pages: https://lovasoa.github.io/marshmallow_dataclass/

Contributing

To install this project and make changes to it locally, follow the instructions in CONTRIBUTING.md.

More Repositories

1

whitebophir

Online collaborative Whiteboard that is simple, free, easy to use and to deploy
JavaScript
1,720
star
2

react-contenteditable

React component for a div with editable contents
TypeScript
1,612
star
3

dezoomify

Dezoomify is a web application to download zoomable images from museum websites, image galleries, and map viewers. Many different zoomable image technologies are supported.
JavaScript
581
star
4

dezoomify-rs

Zoomable image downloader for Google Arts & Culture, Zoomify, IIIF, and others
Rust
437
star
5

bad_json_parsers

Exposing problems in json parsers of several programming languages.
Python
363
star
6

sanipasse

Vérificateur de passe sanitaire open-source
Svelte
176
star
7

json_in_type

Fast json encoder in rust, that encodes the structure of JSON values in their types
Rust
82
star
8

custom_error

Define custom errors without boilerplate using the custom_error! macro.
Rust
70
star
9

ophirofox

Une extension pour navigateur qui permet de lire les articles de presse en ligne sur le compte de bibliothèques ayant souscrit à europresse
JavaScript
59
star
10

pagelabels-py

Python library to manipulate PDF page labels
Python
55
star
11

highs-js

Javascript linear programming library
JavaScript
45
star
12

salesman.js

Solves the traveling salesman problem using simulated annealing.
JavaScript
43
star
13

linear-solve

Small javascript library to solve a system of linear equations, invert a matrix, and nothing more.
JavaScript
38
star
14

bloomfilter

Simplistic (but fast) java implementation of a bloom filter.
Java
37
star
15

mandelbrot

A mandelbrot fractal viewer in javascript using svelte
JavaScript
34
star
16

bin2png

Embed binary data inside an HTML file in an efficient way.
JavaScript
34
star
17

dezoomify-extension

A browser extension to detect zoomable images in web pages and downloading them with dezoomify
JavaScript
33
star
18

TPCH-sqlite

SQLite TPCH database
Shell
32
star
19

Sensitive-Topic-History-Quiz

This is the only place where me, the human is talking. All of the files in this repo were generated by ChatGPT. They required hours of interactions with the language model to make it fix its own bugs, and create coherent components, but I am very proud of the result.
JavaScript
31
star
20

fast_array_intersect

The fastest javascript array intersection function
JavaScript
18
star
21

eml2csv

Convert a collection of eml files to CSV
Python
17
star
22

SQLpage

SQL-only webapp builder, empowering data analysts to build websites and applications quickly
Rust
17
star
23

dia2code

Dia2Code is a small utility used to generate code from a Dia diagram.
C
14
star
24

historique-velib-opendata

Historique des données d'occupation de stations vélib' (publiées en opendata)
Python
13
star
25

musreact

Mustache template to react component compiler
JavaScript
12
star
26

graham-fast

Graham scan implementation in javascript
JavaScript
10
star
27

html2unicode

Node module for transforming HTML into unicode
JavaScript
10
star
28

wordsearch

Search words by regex
Svelte
9
star
29

seamcarving

Seam carving implemented in rust
Rust
9
star
30

ZIF

zif file format documantation and tools
JavaScript
9
star
31

samsung-email-password-decrypt

Decrypt encrypted passwords in EmailProvider.db on samsung phones.
Java
9
star
32

dezoom.sh

Download and assemble tiled images. Dezoomify for bash. Depends on imagemagick
Shell
8
star
33

github-sloc

Firefox extension that prints the number of lines of code of a project on project pages on github.
JavaScript
8
star
34

wikipedia-externallinks-fast-extraction

Fast extraction of all external links from wikipedia
Rust
8
star
35

lagrange-cpp

Lagrange interpolation polynomials in C++11
C++
7
star
36

gnome-keyboard-backlight-menu

Set the keyboard backlight brightness with a slider in gnome shell's system menu.
JavaScript
7
star
37

docurun

JavaScript
6
star
38

rectangle-overlap

Fastly compute the intersection of two rectangles.
TypeScript
6
star
39

pyformat-challenge

Python format string vulnerability exploitation challenge
Python
6
star
40

memoization

Straightforward implementation of memoization in javascript
JavaScript
6
star
41

reg

rÊg is a simple grid game
JavaScript
5
star
42

dezoomify-py

Fork of https://sourceforge.net/projects/dezoomify/
Python
5
star
43

haskell-exercises

Exercices pour apprendre le haskell
Haskell
4
star
44

GoodChat

Simple chat application with ES6 + Vue.js + CouchDB
JavaScript
4
star
45

kdsearch

Search k-dimensional datasets efficiently using KDTrees
Python
4
star
46

secured-file-transfer

Secured file transfer implemented in nodeJS.
JavaScript
4
star
47

expectation-maximization

Multivariate gaussian fit with expectation–maximization (EM) algorithm in javascript.
JavaScript
4
star
48

maya_numerals_converter

Online decimal to maya numeral converter.
HTML
4
star
49

BarcodeDetector-api-demo

A quick demo for the Barcode Detection API
HTML
4
star
50

pff-extract

pff (zoomify single-file image format) to jpeg converter
C
3
star
51

choices

Represent a choice between multiple values, using radio buttons, checkboxes, or HTML's <select> element
Elm
3
star
52

elm-rolling-list

A circular buffer implementation in Elm.
Elm
3
star
53

robots

Multi-agents system where robots go fetch materials.
HTML
2
star
54

RLE

Run-length encoding and decoding in haskell.
Haskell
2
star
55

multivariate-gaussian

Multivariate normal distribution density function implemented in javascript
JavaScript
2
star
56

emotions

Detect emotions from webcam images.
CSS
2
star
57

download-book-of-kells

Shell
2
star
58

parse_wiki_text

Parse wiki text from Mediawiki into a tree of elements
Rust
2
star
59

SuperLogger

Log system information using logstash, store the information on ElasticSearch, and visualize it using Kibana.
Java
2
star
60

elm-jsonpseudolist

Elm Json.Decoder for javascript Array-like objects
Elm
2
star
61

SearchHitIterator

Java iterator for elasticsearch scrolls
Java
2
star
62

setup-emscripten

emscripten github action
JavaScript
2
star
63

sha_hashes

Collection of sha hashes of common passwords
2
star
64

sql2json

Convert sql database dumps to JSON
Rust
2
star
65

2048.lua

lua implementation of the popular game "2048". The aim is to merge tiles until you get a 2048 tile. Original game by @gabrielecirulli on http://gabrielecirulli.github.io/2048/ .
Lua
2
star
66

csv-fill-docx

Fill docx templates with data from a csv file
JavaScript
1
star
67

c-osi

C interface to Open Solver Interface solvers for easy integration with external solvers
C++
1
star
68

lovasoa.github.io

Github pages root
HTML
1
star
69

cemantriche

Cémantriche, pour tricher à cémantix
Jupyter Notebook
1
star
70

resume

Ophir LOJKINE's resume, in the jsonresume format.
1
star
71

lsystems

Haskell implementation of l systems
Haskell
1
star
72

libepeg.js

epeg compiled to javascript. Fast jpeg thumbnailing.
C
1
star
73

doublons-js

Find duplicates files in a folder (search files with similar names). GUI application with node-webkit.
JavaScript
1
star
74

ruzzleplayer

Javascript implementation of an algorithm that plays the mobile game "ruzzle"
JavaScript
1
star
75

ophir_odt_import

Drupal module to import odt (OpenDocument) files into drupal nodes.
PHP
1
star
76

kaigit

Svelte
1
star
77

srtmove-hs

Delay .srt subtitles
Haskell
1
star
78

find-candidate-keys

Finds the candidate keys from a list of functionnal dependencies
JavaScript
1
star
79

comptes

Expenses management for friends
JavaScript
1
star
80

poker

poker probabilities map
JavaScript
1
star
81

omodbus

OModbus is a GUI to interact with modbus devices
HTML
1
star
82

elm-fileinput

<input type="file" /> for Elm
Elm
1
star
83

elm-base-repo

Base repository containing an empty elm module, ready tobe forked.
Elm
1
star
84

dezoomify-browser

This is a small browser that automatically launches dezoomify when it meets a zoomified image. Uses node-webkit.
JavaScript
1
star
85

anylang

Type text in any alphabet. Anylang is a javascript library that converts a phonetic transcription of a text in a language to a text written in the alphabet of the target language. Currently works with hebrew (with vowels) and russian.
JavaScript
1
star
86

qrcode-dataset

A large dataset of partially damaged and distorted QR code images to be used for benchmarking scanning libraries and training new models
Python
1
star
87

srtmove-js

Short javascript program with an HTML interface to move subtitles (add or remove time) to an existing srt file.
JavaScript
1
star
88

dataiku-exercise

US census visualization web application. Given as an exercise by dataiku after a job interview. I didn't get the job.
Elm
1
star