Overview¶
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
Factoryand callload/dumpmethods - Speed. It is up to 10 times faster than
marshmallowanddataclasses.asdict - Automatic name style conversion (e.g.
snake_casetoCamelCase) - 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) boolstr,bytearray,bytesListand common protocols likeIterableare parsed aslistTuple, including something likeTuple[int, ...]orTuple[int, str, int]DictEnumis converted using its valueOptionalAny, using this type no conversion is done during parsing. But serialization is based on real data typeUnionLiteraltypes, including variant fromtyping_extensionsTypedDicttypes with checking oftotal, including variant fromtyping_extensionsdataclassandNamedTupleGenericdataclasses- Other standard types like
datetime,Path,UUIDandIPV4Address - Custom classes can be parsed automatically using info from their
__init__method. Serialization is done by calling vars() function and then processing real data types - Or you can provide custom parser/serializer