Attention
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.
Overview
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.
Requirements
python >= 3.6
You can use dataclass_factory
with python 3.6 and dataclass
library installed from pip.
From python 3.7 it has no external dependencies outside of the Python standard library.
Advantages
No schemas or configuration needed for simple cases. Just create
Factory
and callload
/dump
methodsSpeed. It is up to 10 times faster than
marshmallow
anddataclasses.asdict
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 from 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
Per-field validators
Example
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)
Supported types
numeric types (
int
,float
,Decimal
,complex
,Fraction
)bool
str
,bytearray
,bytes
List
and common protocols likeIterable
are parsed aslist
Tuple
, including something likeTuple[int, ...]
orTuple[int, str, int]
Dict
Enum
is converted using its valueOptional
Any
, using this type no conversion is done during parsing. But serialization is based on real data typeUnion
Literal
types, including variant fromtyping_extensions
TypedDict
types with checking oftotal
, including variant fromtyping_extensions
dataclass
andNamedTuple
Generic
dataclassesOther standard types like
datetime
,Path
,UUID
andIPV4Address
Custom classes can be parsed automatically using info from their
__init__
method. Serialization is done by calling vars() function and then processing real data typesOr you can provide custom parser/serializer