Desert: DRY deserialization¶
docs |
|
---|---|
code |
|
tests |
|
package |
Desert generates serialization schemas for dataclasses
and attrs
classes. Writing
code that’s DRY (“don’t repeat yourself”) helps avoid bugs and improve readability. Desert
helps you write code that’s DRY.
Usage¶
A simple example models two Person
objects in a Car
.
from dataclasses import dataclass
# Or using attrs
# from attr import dataclass
from typing import List
import desert
@dataclass
class Person:
name: str
age: int
@dataclass
class Car:
passengers: List[Person]
# Load some simple data types.
data = {'passengers': [{'name': 'Alice', 'age': 21}, {'name': 'Bob', 'age': 22}]}
# Create a schema for the Car class.
schema = desert.schema(Car)
# Load the data.
car = schema.load(data)
assert car == Car(passengers=[Person(name='Alice', age=21), Person(name='Bob', age=22)])
Documentation¶
Limitations¶
String annotations and forward references inside of functions are not supported.
Acknowledgements¶
This package began as an extension of marshmallow-dataclass to add support for attrs.
Contents¶
Desert: DRY deserialization¶
docs |
|
---|---|
code |
|
tests |
|
package |
Desert generates serialization schemas for dataclasses
and attrs
classes. Writing
code that’s DRY (“don’t repeat yourself”) helps avoid bugs and improve readability. Desert
helps you write code that’s DRY.
Usage¶
A simple example models two Person
objects in a Car
.
from dataclasses import dataclass
# Or using attrs
# from attr import dataclass
from typing import List
import desert
@dataclass
class Person:
name: str
age: int
@dataclass
class Car:
passengers: List[Person]
# Load some simple data types.
data = {'passengers': [{'name': 'Alice', 'age': 21}, {'name': 'Bob', 'age': 22}]}
# Create a schema for the Car class.
schema = desert.schema(Car)
# Load the data.
car = schema.load(data)
assert car == Car(passengers=[Person(name='Alice', age=21), Person(name='Bob', age=22)])
Documentation¶
Limitations¶
String annotations and forward references inside of functions are not supported.
Acknowledgements¶
This package began as an extension of marshmallow-dataclass to add support for attrs.
Usage¶
Basics¶
A simple example models two Person
objects in a Car
.
from dataclasses import dataclass
# Or using attrs
# from attr import dataclass
from typing import List
import desert
@dataclass
class Person:
name: str
age: int
@dataclass
class Car:
passengers: List[Person]
# Load some simple data types.
data = {'passengers': [{'name': 'Alice', 'age': 21}, {'name': 'Bob', 'age': 22}]}
# Create a schema for the Car class.
schema = desert.schema(Car)
# Load the data.
car = schema.load(data)
assert car == Car(passengers=[Person(name='Alice', age=21), Person(name='Bob', age=22)])
Desert can be used with dataclasses
or attr
. With either module,
Desert is able to infer the appropriate marshmallow
field
for any of these types:
enum.Enum
(if you have marshmallow_enum installed.)typing.Union
(if you have marshmallow_union installed, tries each type until one succeeds.)
There are two syntaxes for specifying a field.
In the more concise form, desert.field()
wraps dataclasses.field()
and
desert.ib()
wraps attr.ib()
. These functions take a
marshmallow.fields.Field
as the first argument, and the remaining arguments are
forwarded to the corresponding wrapped function.
In the more verbose form, simply use the normal functions dataclasses.field()
and
attr.ib()
, but provide the metadata
value using desert.metadata()
,
which returns a dict of values namespaced for desert
to use.
Use with dataclasses
¶
import dataclasses
import datetime
import desert
import marshmallow
@dataclasses.dataclass
class Entry:
timestamp: str = desert.field(marshmallow.fields.NaiveDateTime())
# Or use the more verbose form.
favorite_number: int = dataclasses.field(default=3, metadata=desert.metadata(field=marshmallow.fields.Int()))
schema = desert.schema(Entry)
print(schema.load({"timestamp": "2019-10-21T10:25:00", "favorite_number": 42}))
Entry(timestamp=datetime.datetime(2019, 10, 21, 10, 25), favorite_number=42)
Use with attrs
¶
import datetime
import attr
import desert
import marshmallow
@attr.dataclass
class Entry:
timestamp: str = desert.ib(marshmallow.fields.NaiveDateTime())
# Or use the more verbose form.
favorite_number: int = attr.ib(default=3, metadata=desert.metadata(field=marshmallow.fields.Int()))
schema = desert.schema(Entry)
print(schema.load({"timestamp": "2019-10-21T10:25:00", "favorite_number": 42}))
Entry(timestamp=datetime.datetime(2019, 10, 21, 10, 25), favorite_number=42)
Schema meta parameters¶
Any marshmallow.Schema.Meta
value is accepted in the meta dict. For example, to exclude unknown values during deserialization:
import attr
import desert
@attr.dataclass
class A:
x: int
schema = desert.schema_class(A, meta={"unknown": marshmallow.EXCLUDE})()
print(schema.load({"x": 1, "y": 2}))
A(x=1)
Reference¶
desert package¶
Submodules¶
desert.exceptions module¶
-
exception
desert.exceptions.
DesertException
[source]¶ Bases:
Exception
Top-level exception for desert.
-
exception
desert.exceptions.
NotAnAttrsClassOrDataclass
[source]¶ Bases:
desert.exceptions.DesertException
Raised for dataclass operations on non-dataclasses.
-
exception
desert.exceptions.
UnknownType
[source]¶ Bases:
desert.exceptions.DesertException
Raised for a type with unknown serialization equivalent.
Module contents¶
-
desert.
field
(marshmallow_field, **kw)[source]¶ Specify a marshmallow field in the metadata for a
dataclasses.dataclass
.@dataclasses.dataclass class A: x: int = desert.field(marshmallow.fields.Int())
- Return type
-
desert.
ib
(marshmallow_field, **kw)[source]¶ Specify a marshmallow field in the metadata for an
attr.dataclass
.@attr.dataclass class A: x: int = desert.ib(marshmallow.fields.Int())
- Return type
_CountingAttr
-
desert.
metadata
(field)[source]¶ Specify a marshmallow field in the field metadata.
x: int = attr.ib(metadata=desert.metadata(marshmallow.fields.Int()))
Contributing¶
Contributions are welcome, and they are greatly appreciated! Every little bit helps, and credit will always be given.
Bug reports¶
When reporting a bug please include:
Your operating system name and version.
Any details about your local setup that might be helpful in troubleshooting.
Detailed steps to reproduce the bug.
Documentation improvements¶
desert could always use more documentation, whether as part of the official desert docs, in docstrings, or even on the web in blog posts, articles, and such.
Feature requests and feedback¶
The best way to send feedback is to file an issue at https://github.com/python-desert/desert/issues.
If you are proposing a feature:
Explain in detail how it would work.
Keep the scope as narrow as possible, to make it easier to implement.
Remember that this is a volunteer-driven project, and that code contributions are welcome :)
Development¶
To set up desert for local development:
Fork desert (look for the “Fork” button).
Clone your fork locally:
git clone git@github.com:your_name_here/desert.git
Create a branch for local development:
git checkout -b name-of-your-bugfix-or-feature
Now you can make your changes locally.
When you’re done making changes, run all the checks, doc builder and spell checker with tox one command:
tox
Commit your changes and push your branch to GitHub:
git add . git commit -m "Your detailed description of your changes." git push origin name-of-your-bugfix-or-feature
Submit a pull request through the GitHub website.
Pull Request Guidelines¶
If you need some code review or feedback while you’re developing the code just make the pull request.
For merging, you should:
Include passing tests (run
tox
) 1.Update documentation when there’s new API, functionality etc.
Add a file in
changelog.d/
describing the changes. The filename should be{id}.{type}.rst
, where{id}
is the number of the GitHub issue or pull request and{type}
is one ofbreaking
(for breaking changes),deprecation
(for deprecations), orchange
(for non-breaking changes). For example, to add a new feature requested in GitHub issue #1234, add a file calledchangelog.d/1234.change.rst
describing the change.Add yourself to
AUTHORS.rst
.
- 1
If you don’t have all the necessary python versions available locally you can rely on Travis - it will run the tests for each change you add in the pull request.
It will be slower though …
Tips¶
To run a subset of tests:
tox -e envname -- pytest -k test_myfeature
To run all the test environments in parallel (you need to pip install detox
):
detox
Authors¶
A full list of contributors is available in the GitHub repository.
Changelog¶
2020.01.06 (2020-01-06)¶
2020.01.05 (2020-01-05)¶
2020.01.04 (2020-01-04)¶
2019.12.10¶
2019.12.09¶
2019.11.06 (2019-11-06)¶
Changes¶
Switch to calver
Backward-incompatible Changes¶
Non-optional fields without a default or factory now have required=True so raise
marshmallow.exceptions.ValidationError
when missing. #1