Giter Club home page Giter Club logo

marshmallow-attrs's Introduction

Overview

docs Documentation Status
tests
Travis-CI Build Status
Coverage Status
package
PyPI Package latest release PyPI Wheel Supported versions Supported implementations
Commits since latest release

Marshmallow schemas for attrs classes

Automatic generation of marshmallow schemas from dataclasses.

This package is based on marshmallow-dataclass.

Specifying a schema to which your data should conform is very useful, both for (de)serialization and for documentation. However, using schemas in python often means having both a class to represent your data and a class to represent its schema, which means duplicated code that could fall out of sync. With the new features of python 3.6, types can be defined for class members, and that allows libraries like this one to generate schemas automatically.

An use case would be to document APIs (with flasgger, for instance) in a way that allows you to statically check that the code matches the documentation.

Installation

pip install marshmallow-attrs

Documentation

https://marshmallow-attrs.readthedocs.io/

Usage

You simply import `marshmallow_attrs.dataclass instead of attr.dataclass. It adds a Schema property to the generated class, containing a marshmallow Schema class.

If you need to specify custom properties on your marshmallow fields (such as attribute, error, validate, required, dump_only, error_messages, description ...) you can add them using the metadata argument of the attr.ib function.

import attr
from marshmallow_attrs import dataclass # Importing from marshmallow_attrs instead of attrs
import marshmallow.validate
from typing import List, Optional

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


@dataclass
class City:
  name: Optional[str]
  buildings: List[Building] = attr.ib(factory=list)

# City.Schema contains a marshmallow schema class
city, _ = City.Schema().load({
    "name": "Paris",
    "buildings": [
        {"name": "Eiffel Tower", "height":324}
    ]
})

# Serializing city as a json string
city_json, _ = City.Schema().dumps(city)

The previous syntax is very convenient, as the only change you have to apply to your existing code is update the dataclass import.

However, as the .Schema property is added dynamically, it can confuse type checkers. If you want to avoid that, you can also use the standard attr.s decorator, and generate the schema manually using class_schema :

import attr


from datetime import datetime
import marshmallow_attrs

@attr.dataclass
class Person:
    name: str
    birth: datetime

PersonSchema = marshmallow_attrs.class_schema(Person)

You can also declare the schema as a ClassVar:

from marshmallow_attrs import dataclass
from marshmallow import Schema
from typing import ClassVar, Type

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

You can specify the Meta just as you would in a marshmallow Schema:

from marshmallow_attrs import dataclass

@dataclass
class Point:
  x:float
  y:float
  class Meta:
    ordered = True

Installation

This package is hosted on pypi :

pip install marshmallow-attrs

Documentation

The project documentation is hosted on readthedocs.

Usage warning

This library depends on python's standard typing library, which is provisional.

Credits

This package is based on marshmallow-dataclass.

marshmallow-attrs's People

Contributors

adamboche avatar evanfwelch avatar karlb avatar lovasoa avatar probot-auto-merge[bot] avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.