An extension to Python's dataclasses that provides type validation and common data conversion functions.
from dataclasses import dataclass
from dataclass_mixins import DataclassMixin
@dataclass(frozen=True)
class A(DataclassMixin):
a_a: int
b_b: str
a = A.create()
a = A.create_strictly(a=1, b='b')
a.serialize()
# {'a_a': 1, 'b_b': 'b'}
a.to_camel_case_json()
# {'aA': 1, 'bB': 'b'}| File | Stmts | Miss | Cover(%) | Missing |
|---|---|---|---|---|
| dataclass_mixin.py | 256 | 1 | 99.61 | 28 |
| rule.py | 73 | 0 | 100 | |
| TOTAL | 329 | 1 | 99.7 |
When a field is not assigned a value, the default value will be determined based on the following conditions:
- Use the
defaultordefault_factorydefined in the field - If the field has multiple types and includes
None, the default value will beNone - If the first type of the field is
list,set, ordict, create the corresponding container - If the first type of the field is a
dataclass, create an emptydataclass - If none of the above conditions are met, the default value will be
None
- During creation, the type of provided parameters will be checked against the types defined in the dataclass
DataclassMixin.create_strictly()will check if parameter names match the dataclass fields
Convert data to dataclass as much as possible
- value to value
dictor custom class to dataclass- value to
Enum int,float,Decimal, or datestrtodatetimestrtoUUID
Special handling for the following cases:
Enumto value: Check if the value matches the typedatetimetoint: Convert toint(timestamp())datetimetofloatorDecimal: Convert totimestamp()UUIDtostr: Convert tostr(uuid)
Standard kwargs format
Works the same as DataclassMixin.create(), but checks if parameter names match dataclass fields
Convert camel case JSON to dataclass, for example, converting frontend payload to dataclass
- Convert object to dataclass, for example, converting entity to API response dataclass
- Will raise error if object type is
dict, suggesting to usecreate()orcreate_from_camel_case_json() - Will raise error if object type is in
str, int, float, bool, datetime, Enum, list, tuple, set
Use dataclasses.asdict() for conversion, with special handling for:
Enum: Convert tovaluedatetime: Convert totimestamp()UUID: Convert tostr(uuid)
Basic conversion
Convert all field names to camel case
Convert all field names to snake case
pip install -r tests/requirements.txt
PYTHONPATH=./ pytest --cov=src/ --cov-report=term-missing tests -vv -s