A comprehensive dataclass instance creation library that enables bidirectional conversion between dictionaries and dataclass instances.
npx @tessl/cli install tessl/pypi-dataclass-factory@1.1.00
# Dataclass Factory
1
2
A comprehensive Python library that provides bidirectional conversion between dictionaries and dataclass instances. It fills the gap left by Python's standard `asdict()` method by enabling conversion from dictionaries back to dataclass objects with flexible parsing capabilities, custom type handling, and naming policy support.
3
4
## Package Information
5
6
- **Package Name**: dataclass_factory
7
- **Package Type**: Library
8
- **Language**: Python
9
- **Installation**: `pip install dataclass_factory`
10
11
## Core Imports
12
13
```python
14
from dataclass_factory import ParserFactory, SerializerFactory, NameStyle
15
```
16
17
For simple use cases, you can use the convenience function:
18
19
```python
20
from dataclass_factory import parse
21
```
22
23
For legacy compatibility with dataclasses.asdict():
24
25
```python
26
from dataclass_factory import dict_factory
27
```
28
29
## Basic Usage
30
31
```python
32
from dataclasses import dataclass
33
from dataclass_factory import ParserFactory, SerializerFactory
34
35
@dataclass
36
class User:
37
name: str
38
age: int
39
email: str = "unknown@example.com"
40
41
# Create parser and serializer factories
42
parser_factory = ParserFactory()
43
serializer_factory = SerializerFactory()
44
45
# Convert dict to dataclass
46
user_data = {
47
"name": "John Doe",
48
"age": 30
49
}
50
51
user = parser_factory.get_parser(User)(user_data)
52
# Result: User(name="John Doe", age=30, email="unknown@example.com")
53
54
# Convert dataclass back to dict
55
user_dict = serializer_factory.get_serializer(User)(user)
56
# Result: {"name": "John Doe", "age": 30, "email": "unknown@example.com"}
57
```
58
59
## Architecture
60
61
The library uses a factory pattern with caching for optimal performance:
62
63
- **ParserFactory**: Creates and caches parsers for converting dicts to dataclass instances
64
- **SerializerFactory**: Creates and caches serializers for converting dataclass instances to dicts
65
- **Type Detection**: Automatically handles complex types including Optional, Union, collections, and custom classes
66
- **Naming Policies**: Supports different field naming conventions (snake_case, camelCase, kebab-case)
67
- **Custom Type Factories**: Extensible system for handling custom types and complex parsing scenarios
68
69
## Capabilities
70
71
### Data Parsing
72
73
Convert dictionaries and other data structures into dataclass instances with support for complex nested types, Optional fields, Union types, collections, and custom parsing logic.
74
75
```python { .api }
76
class ParserFactory:
77
def __init__(
78
self,
79
trim_trailing_underscore: bool = True,
80
debug_path: bool = False,
81
type_factories: Dict[Type, Parser] = None,
82
name_styles: Dict[Type, NameStyle] = None,
83
): ...
84
85
def get_parser(self, cls: ClassVar) -> Parser: ...
86
87
def parse(
88
data,
89
cls,
90
trim_trailing_underscore: bool = True,
91
type_factories: Dict[Any, Callable] = None,
92
): ...
93
```
94
95
[Data Parsing](./parsing.md)
96
97
### Data Serialization
98
99
Convert dataclass instances back to dictionaries with performance optimization (up to 10x faster than standard asdict), custom serializers, and naming policy support.
100
101
```python { .api }
102
class SerializerFactory:
103
def __init__(
104
self,
105
trim_trailing_underscore: bool = True,
106
debug_path: bool = False,
107
type_serializers: Dict[Type, Serializer] = None,
108
name_styles: Dict[Type, NameStyle] = None,
109
): ...
110
111
def get_serializer(self, cls: Any) -> Serializer: ...
112
```
113
114
[Data Serialization](./serialization.md)
115
116
### Naming Policies
117
118
Convert between different field naming conventions when parsing and serializing dataclasses, supporting snake_case, camelCase, kebab-case, and CamelCase transformations.
119
120
```python { .api }
121
class NameStyle(Enum):
122
snake = "snake_case"
123
kebab = "kebab-case"
124
camel_lower = "camelCaseLower"
125
camel = "CamelCase"
126
127
def convert_name(
128
name: str,
129
trim_trailing_underscore: bool = True,
130
naming_policy: NameStyle = None
131
) -> str: ...
132
```
133
134
[Naming Policies](./naming.md)
135
136
## Types
137
138
```python { .api }
139
from typing import Callable, Any, Dict, Type
140
141
# Note: These type aliases are used internally but not officially exported
142
Parser = Callable[[Any], Any]
143
Serializer = Callable[[Any], Any]
144
```
145
146
## Supported Data Types
147
148
The library supports parsing and serialization for:
149
150
- **Dataclasses**: Primary target type with full field support
151
- **Basic Types**: int, float, complex, bool, str, bytes, bytearray
152
- **Decimal**: decimal.Decimal with string parsing
153
- **Enums**: Parsed from and serialized to values
154
- **Collections**: List, Set, FrozenSet, Deque with typed elements
155
- **Tuples**: Both typed tuples and ellipsis syntax
156
- **Dictionaries**: Dict with typed keys and values
157
- **Optional**: Optional types with None handling
158
- **Union**: Union types with ordered parsing attempts
159
- **Any**: Pass-through for untyped data
160
- **Custom Classes**: Based on __init__ method signatures