or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

core-serialization.mdfield-configuration.mdformat-modules.mdindex.mdtype-system.mdunion-handling.md

core-serialization.mddocs/

0

# Core Serialization

1

2

The fundamental serialization and deserialization functionality that powers all format-specific modules in pyserde. This module provides the core @serde decorator and basic conversion functions for dictionaries and tuples.

3

4

## Capabilities

5

6

### The @serde Decorator

7

8

The main decorator that enables automatic serialization and deserialization for dataclasses. When applied to a class, it generates optimized serialization and deserialization functions.

9

10

```python { .api }

11

def serde(

12

_cls=None,

13

rename_all: str | None = None,

14

reuse_instances_default: bool = True,

15

convert_sets_default: bool = False,

16

serializer: SerializeFunc | None = None,

17

deserializer: DeserializeFunc | None = None,

18

tagging: Tagging = DefaultTagging,

19

type_check: TypeCheck = strict,

20

serialize_class_var: bool = False,

21

class_serializer: ClassSerializer | None = None,

22

class_deserializer: ClassDeserializer | None = None,

23

deny_unknown_fields: bool = False,

24

) -> Any:

25

"""

26

Main decorator that combines serialize and deserialize functionality.

27

28

Parameters:

29

- _cls: The class to decorate

30

- rename_all: Case conversion strategy ('camelCase', 'PascalCase', 'kebab-case', 'SCREAMING_SNAKE_CASE')

31

- reuse_instances_default: Whether to reuse instances during deserialization

32

- convert_sets_default: Whether to convert sets to lists during serialization

33

- serializer: Custom serializer function for the entire class

34

- deserializer: Custom deserializer function for the entire class

35

- tagging: Union tagging strategy (ExternalTagging, InternalTagging, AdjacentTagging, Untagged)

36

- type_check: Type checking mode (strict, disabled, coerce)

37

- serialize_class_var: Whether to serialize ClassVar fields

38

- class_serializer: Custom class serializer object

39

- class_deserializer: Custom class deserializer object

40

- deny_unknown_fields: Whether to raise error on unknown fields during deserialization

41

42

Returns:

43

Decorated class with serialization/deserialization capabilities

44

"""

45

```

46

47

### Dictionary Conversion

48

49

Convert objects to and from Python dictionaries, the foundation for all other serialization formats.

50

51

```python { .api }

52

def to_dict(

53

o: Any,

54

c: Optional[type[Any]] = None,

55

reuse_instances: Optional[bool] = None,

56

convert_sets: Optional[bool] = None,

57

skip_none: bool = False,

58

) -> dict[Any, Any]:

59

"""

60

Serialize object to dictionary.

61

62

Parameters:

63

- o: Object to serialize

64

- c: Optional class hint for serialization

65

- reuse_instances: Whether to reuse instances (affects object identity)

66

- convert_sets: Whether to convert sets to lists

67

- skip_none: Whether to skip None values

68

69

Returns:

70

Dictionary representation of the object

71

"""

72

73

def from_dict(cls: type[T], o: dict[str, Any], reuse_instances: Optional[bool] = None) -> T:

74

"""

75

Deserialize dictionary to object.

76

77

Parameters:

78

- cls: Target class type

79

- o: Dictionary data to deserialize

80

- reuse_instances: Whether to reuse instances during deserialization

81

82

Returns:

83

Instance of cls populated from dictionary data

84

"""

85

86

def asdict(v: Any) -> dict[Any, Any]:

87

"""

88

Serialize object to dict without reuse_instances optimization.

89

90

Parameters:

91

- v: Object to serialize

92

93

Returns:

94

Dictionary representation without instance reuse

95

"""

96

```

97

98

### Tuple Conversion

99

100

Convert objects to and from Python tuples for ordered serialization.

101

102

```python { .api }

103

def to_tuple(

104

o: Any,

105

c: Optional[type[Any]] = None,

106

reuse_instances: Optional[bool] = None,

107

convert_sets: Optional[bool] = None,

108

skip_none: bool = False,

109

) -> tuple[Any, ...]:

110

"""

111

Serialize object to tuple.

112

113

Parameters:

114

- o: Object to serialize

115

- c: Optional class hint for serialization

116

- reuse_instances: Whether to reuse instances

117

- convert_sets: Whether to convert sets to lists

118

- skip_none: Whether to skip None values

119

120

Returns:

121

Tuple representation of the object

122

"""

123

124

def from_tuple(cls: type[T], o: Any, reuse_instances: Optional[bool] = None) -> T:

125

"""

126

Deserialize tuple to object.

127

128

Parameters:

129

- cls: Target class type

130

- o: Tuple data to deserialize

131

- reuse_instances: Whether to reuse instances during deserialization

132

133

Returns:

134

Instance of cls populated from tuple data

135

"""

136

137

def astuple(v: Any) -> tuple[Any, ...]:

138

"""

139

Serialize object to tuple without reuse_instances optimization.

140

141

Parameters:

142

- v: Object to serialize

143

144

Returns:

145

Tuple representation without instance reuse

146

"""

147

```

148

149

### Serialization Control

150

151

Functions to control and customize the serialization behavior.

152

153

```python { .api }

154

def serialize(

155

_cls: Optional[type[T]] = None,

156

rename_all: Optional[str] = None,

157

reuse_instances_default: bool = False,

158

convert_sets_default: bool = False,

159

serializer: Optional[SerializeFunc] = None,

160

tagging: Tagging = DefaultTagging,

161

type_check: TypeCheck = strict,

162

serialize_class_var: bool = False,

163

class_serializer: Optional[ClassSerializer] = None,

164

**kwargs: Any,

165

) -> Any:

166

"""

167

Decorator to make a class serializable.

168

169

Parameters:

170

- _cls: Class to make serializable

171

- rename_all: Case conversion strategy

172

- reuse_instances_default: Default reuse_instances setting

173

- convert_sets_default: Default convert_sets setting

174

- serializer: Custom serializer function

175

- tagging: Union tagging strategy

176

- type_check: Type checking mode

177

- serialize_class_var: Whether to serialize ClassVar fields

178

- class_serializer: Custom class serializer

179

- **kwargs: Additional arguments

180

181

Returns:

182

Class with serialization capability

183

"""

184

185

def deserialize(

186

_cls: Optional[type[T]] = None,

187

rename_all: Optional[str] = None,

188

reuse_instances_default: bool = True,

189

convert_sets_default: bool = False,

190

deserializer: Optional[DeserializeFunc] = None,

191

tagging: Tagging = DefaultTagging,

192

type_check: TypeCheck = strict,

193

class_deserializer: Optional[ClassDeserializer] = None,

194

deny_unknown_fields: bool = False,

195

**kwargs: Any,

196

) -> Any:

197

"""

198

Decorator to make a class deserializable.

199

200

Parameters:

201

- _cls: Class to make deserializable

202

- rename_all: Case conversion strategy

203

- reuse_instances_default: Default reuse_instances setting

204

- convert_sets_default: Default convert_sets setting

205

- deserializer: Custom deserializer function

206

- tagging: Union tagging strategy

207

- type_check: Type checking mode

208

- class_deserializer: Custom class deserializer

209

- deny_unknown_fields: Whether to raise error on unknown fields

210

- **kwargs: Additional arguments

211

212

Returns:

213

Class with deserialization capability

214

"""

215

216

def is_serializable(instance_or_class: Any) -> bool:

217

"""

218

Test if instance or class is serializable.

219

220

Parameters:

221

- instance_or_class: Object instance or class to test

222

223

Returns:

224

True if serializable, False otherwise

225

"""

226

227

def is_deserializable(instance_or_class: Any) -> bool:

228

"""

229

Test if instance or class is deserializable.

230

231

Parameters:

232

- instance_or_class: Object instance or class to test

233

234

Returns:

235

True if deserializable, False otherwise

236

"""

237

```

238

239

## Usage Examples

240

241

### Basic Usage

242

243

```python

244

from serde import serde, to_dict, from_dict

245

246

@serde

247

class Person:

248

name: str

249

age: int

250

email: str | None = None

251

252

person = Person("Alice", 30, "alice@example.com")

253

data = to_dict(person) # {'name': 'Alice', 'age': 30, 'email': 'alice@example.com'}

254

person_copy = from_dict(Person, data)

255

```

256

257

### Case Conversion

258

259

```python

260

@serde(rename_all='camelCase')

261

class UserProfile:

262

user_name: str

263

first_name: str

264

last_name: str

265

266

profile = UserProfile("alice123", "Alice", "Smith")

267

data = to_dict(profile) # {'userName': 'alice123', 'firstName': 'Alice', 'lastName': 'Smith'}

268

```

269

270

### Custom Serializers

271

272

```python

273

def custom_date_serializer(obj):

274

return obj.isoformat()

275

276

def custom_date_deserializer(cls, data):

277

return cls.fromisoformat(data)

278

279

@serde(

280

serializer=custom_date_serializer,

281

deserializer=custom_date_deserializer

282

)

283

class Event:

284

name: str

285

date: datetime.date

286

```