dataclass_factory is a modern way to convert dataclasses or other objects to and from more common types like dicts
Important
The new major version is out The library was renamed to adaptix due to extending of the working scope.
This update features:
- Support for model-to-model conversion.
- Support for attrs and sqlalchemy (integration with many other libraries is coming).
- Fully redesigned API helping to follow DRY.
- Performance improvements of up to two times
See documentation for more details.
Install
pip install dataclass_factory
Use
from dataclasses import dataclass
import dataclass_factory
@dataclass
class Book:
title: str
price: int
author: str = "Unknown author"
data = {
"title": "Fahrenheit 451",
"price": 100,
}
factory = dataclass_factory.Factory()
book: Book = factory.load(data, Book) # Same as Book(title="Fahrenheit 451", price=100)
serialized = factory.dump(book)
- python >= 3.6
You can use dataclass_factory
with python 3.6 and dataclass
library installed from pip.
On python 3.7 it has no external dependencies outside of the Python standard library.
- No schemas or configuration needed for simple cases. Just create
Factory
and callload
/dump
methods - Speed. It is up to 10 times faster than
marshmallow
anddataclasses.asdict
(see benchmarks) - Automatic name style conversion (e.g.
snake_case
toCamelCase
) - Automatic skipping of "internal use" fields (with leading underscore)
- Enums, typed dicts, tuples and lists are supported out of the box
- Unions and Optionals are supported without need to define them in schema
- Generic dataclasses can be automatically parsed as well
- Cyclic-referenced structures (such as linked-lists or trees) also can be converted
- Validators, custom parser steps are supported.
- Multiple schemas for single type can be provided to support different ways of parsing of the same type