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

format-modules.mddocs/

0

# Format-Specific Modules

1

2

pyserde provides dedicated modules for serializing to and from specific data formats. Each format module follows the same pattern with `to_format` and `from_format` functions, plus optional serializer classes for advanced usage.

3

4

## Capabilities

5

6

### JSON Serialization

7

8

JSON format support with both Python's standard json module and optional orjson for performance.

9

10

```python { .api }

11

def to_json(

12

obj: Any,

13

cls: Optional[Any] = None,

14

se: type[Serializer[str]] = JsonSerializer,

15

reuse_instances: bool = False,

16

convert_sets: bool = True,

17

skip_none: bool = False,

18

**opts: Any,

19

) -> str:

20

"""

21

Serialize object to JSON string. orjson will be used if available.

22

23

Parameters:

24

- obj: Object to serialize

25

- cls: Optional class hint for serialization

26

- se: Serializer class to use (JsonSerializer by default)

27

- reuse_instances: Whether to reuse object instances

28

- convert_sets: Whether to convert sets to lists

29

- skip_none: Whether to skip None values

30

- **opts: Additional arguments passed to json.dumps() or orjson.dumps()

31

32

Returns:

33

JSON string representation

34

"""

35

36

def from_json(

37

c: type[T],

38

s: AnyStr,

39

de: type[Deserializer[AnyStr]] = JsonDeserializer,

40

**opts: Any

41

) -> T:

42

"""

43

Deserialize JSON string to object. orjson will be used if available.

44

45

Parameters:

46

- c: Target class type

47

- s: JSON string or bytes to deserialize

48

- de: Deserializer class to use (JsonDeserializer by default)

49

- **opts: Additional arguments passed to json.loads() or orjson.loads()

50

51

Returns:

52

Instance of class c populated from JSON data

53

"""

54

55

class JsonSerializer(Serializer[str]):

56

"""JSON serializer class for advanced usage."""

57

58

@classmethod

59

def serialize(cls, obj: Any, **opts: Any) -> str: ...

60

61

class JsonDeserializer(Deserializer[AnyStr]):

62

"""JSON deserializer class for advanced usage."""

63

64

@classmethod

65

def deserialize(cls, data: AnyStr, **opts: Any) -> Any: ...

66

```

67

68

### YAML Serialization

69

70

YAML format support using PyYAML library for human-readable configuration files.

71

72

```python { .api }

73

def to_yaml(

74

obj: Any,

75

cls: Optional[Any] = None,

76

se: type[Serializer[str]] = YamlSerializer,

77

reuse_instances: bool = False,

78

convert_sets: bool = True,

79

skip_none: bool = False,

80

**opts: Any,

81

) -> str:

82

"""

83

Serialize object to YAML string.

84

85

Parameters:

86

- obj: Object to serialize

87

- cls: Optional class hint for serialization

88

- se: Serializer class to use (YamlSerializer by default)

89

- reuse_instances: Whether to reuse object instances

90

- convert_sets: Whether to convert sets to lists

91

- skip_none: Whether to skip None values

92

- **opts: Additional arguments passed to yaml.safe_dump()

93

94

Returns:

95

YAML string representation

96

"""

97

98

def from_yaml(

99

c: type[T],

100

s: str,

101

de: type[Deserializer[str]] = YamlDeserializer,

102

**opts: Any

103

) -> T:

104

"""

105

Deserialize YAML string to object.

106

107

Parameters:

108

- c: Target class type

109

- s: YAML string to deserialize

110

- de: Deserializer class to use (YamlDeserializer by default)

111

- **opts: Additional arguments passed to yaml.safe_load()

112

113

Returns:

114

Instance of class c populated from YAML data

115

"""

116

117

class YamlSerializer(Serializer[str]):

118

"""YAML serializer class for advanced usage."""

119

120

@classmethod

121

def serialize(cls, obj: Any, **opts: Any) -> str: ...

122

123

class YamlDeserializer(Deserializer[str]):

124

"""YAML deserializer class for advanced usage."""

125

126

@classmethod

127

def deserialize(cls, data: str, **opts: Any) -> Any: ...

128

```

129

130

### TOML Serialization

131

132

TOML format support for configuration files, using tomli and tomli-w libraries.

133

134

```python { .api }

135

def to_toml(

136

obj: Any,

137

cls: Optional[Any] = None,

138

se: type[Serializer[str]] = TomlSerializer,

139

reuse_instances: bool = False,

140

convert_sets: bool = True,

141

skip_none: bool = True,

142

**opts: Any,

143

) -> str:

144

"""

145

Serialize object to TOML string.

146

147

Parameters:

148

- obj: Object to serialize

149

- cls: Optional class hint for serialization

150

- se: Serializer class to use (TomlSerializer by default)

151

- reuse_instances: Whether to reuse object instances

152

- convert_sets: Whether to convert sets to lists

153

- skip_none: Whether to skip None values (defaults to True for TOML)

154

- **opts: Additional arguments passed to tomli_w.dumps()

155

156

Returns:

157

TOML string representation

158

"""

159

160

def from_toml(

161

c: type[T],

162

s: str,

163

de: type[Deserializer[str]] = TomlDeserializer,

164

**opts: Any

165

) -> T:

166

"""

167

Deserialize TOML string to object.

168

169

Parameters:

170

- c: Target class type

171

- s: TOML string to deserialize

172

- de: Deserializer class to use (TomlDeserializer by default)

173

- **opts: Additional arguments passed to tomllib.loads()

174

175

Returns:

176

Instance of class c populated from TOML data

177

"""

178

179

class TomlSerializer(Serializer[str]):

180

"""TOML serializer class for advanced usage."""

181

182

@classmethod

183

def serialize(cls, obj: Any, **opts: Any) -> str: ...

184

185

class TomlDeserializer(Deserializer[str]):

186

"""TOML deserializer class for advanced usage."""

187

188

@classmethod

189

def deserialize(cls, data: str, **opts: Any) -> Any: ...

190

```

191

192

### MessagePack Serialization

193

194

Efficient binary serialization using MessagePack format for performance-critical applications.

195

196

```python { .api }

197

def to_msgpack(

198

obj: Any,

199

cls: Optional[Any] = None,

200

se: type[Serializer[bytes]] = MsgPackSerializer,

201

named: bool = True,

202

ext_dict: Optional[dict[type[Any], int]] = None,

203

reuse_instances: bool = False,

204

convert_sets: bool = True,

205

**opts: Any,

206

) -> bytes:

207

"""

208

Serialize object to MessagePack bytes.

209

210

Parameters:

211

- obj: Object to serialize

212

- cls: Optional class hint for serialization

213

- se: Serializer class to use (MsgPackSerializer by default)

214

- named: If True, encode as dict; if False, encode as tuple for compact output

215

- ext_dict: Optional dict mapping types to extension type codes

216

- reuse_instances: Whether to reuse object instances

217

- convert_sets: Whether to convert sets to lists

218

- **opts: Additional arguments passed to msgpack.packb()

219

220

Returns:

221

MessagePack binary data

222

"""

223

224

def from_msgpack(

225

c: type[T],

226

s: bytes,

227

de: type[Deserializer[bytes]] = MsgPackDeserializer,

228

named: bool = True,

229

ext_dict: Optional[dict[int, type[Any]]] = None,

230

skip_none: bool = False,

231

**opts: Any,

232

) -> T:

233

"""

234

Deserialize MessagePack bytes to object.

235

236

Parameters:

237

- c: Target class type

238

- s: MessagePack binary data to deserialize

239

- de: Deserializer class to use (MsgPackDeserializer by default)

240

- named: If True, decode from dict; if False, decode from tuple

241

- ext_dict: Optional dict mapping extension type codes to types

242

- skip_none: Whether to skip None values

243

- **opts: Additional arguments passed to msgpack.unpackb()

244

245

Returns:

246

Instance of class c populated from MessagePack data

247

"""

248

249

class MsgPackSerializer(Serializer[bytes]):

250

"""MessagePack serializer class for advanced usage."""

251

252

@classmethod

253

def serialize(

254

cls,

255

obj: Any,

256

use_bin_type: bool = True,

257

ext_type_code: Optional[int] = None,

258

**opts: Any

259

) -> bytes: ...

260

261

class MsgPackDeserializer(Deserializer[bytes]):

262

"""MessagePack deserializer class for advanced usage."""

263

264

@classmethod

265

def deserialize(

266

cls,

267

data: bytes,

268

raw: bool = False,

269

use_list: bool = False,

270

**opts: Any

271

) -> Any: ...

272

```

273

274

### Pickle Serialization

275

276

Python pickle format support for complete Python object serialization.

277

278

```python { .api }

279

def to_pickle(

280

obj: Any,

281

cls: Optional[Any] = None,

282

se: type[Serializer[bytes]] = PickleSerializer,

283

reuse_instances: bool = False,

284

convert_sets: bool = True,

285

skip_none: bool = False,

286

**opts: Any,

287

) -> bytes:

288

"""

289

Serialize object to pickle bytes.

290

291

Parameters:

292

- obj: Object to serialize

293

- cls: Optional class hint for serialization

294

- se: Serializer class to use (PickleSerializer by default)

295

- reuse_instances: Whether to reuse object instances

296

- convert_sets: Whether to convert sets to lists

297

- skip_none: Whether to skip None values

298

- **opts: Additional arguments passed to pickle.dumps()

299

300

Returns:

301

Pickle binary data

302

"""

303

304

def from_pickle(

305

c: type[T],

306

data: bytes,

307

de: type[Deserializer[bytes]] = PickleDeserializer,

308

**opts: Any

309

) -> T:

310

"""

311

Deserialize pickle bytes to object.

312

313

Parameters:

314

- c: Target class type

315

- data: Pickle binary data to deserialize

316

- de: Deserializer class to use (PickleDeserializer by default)

317

- **opts: Additional arguments passed to pickle.loads()

318

319

Returns:

320

Instance of class c populated from pickle data

321

"""

322

323

class PickleSerializer(Serializer[bytes]):

324

"""Pickle serializer class for advanced usage."""

325

326

@classmethod

327

def serialize(cls, obj: Any, **opts: Any) -> bytes: ...

328

329

class PickleDeserializer(Deserializer[bytes]):

330

"""Pickle deserializer class for advanced usage."""

331

332

@classmethod

333

def deserialize(cls, data: bytes, **opts: Any) -> Any: ...

334

```

335

336

## Usage Examples

337

338

### JSON Example

339

340

```python

341

from serde import serde

342

from serde.json import to_json, from_json

343

344

@serde

345

class Config:

346

host: str

347

port: int

348

debug: bool = False

349

350

config = Config("localhost", 8080, True)

351

json_str = to_json(config)

352

# '{"host":"localhost","port":8080,"debug":true}'

353

354

config_copy = from_json(Config, json_str)

355

# Config(host='localhost', port=8080, debug=True)

356

```

357

358

### YAML Example

359

360

```python

361

from serde import serde

362

from serde.yaml import to_yaml, from_yaml

363

364

@serde

365

class DatabaseConfig:

366

host: str

367

port: int

368

username: str

369

password: str

370

371

db_config = DatabaseConfig("db.example.com", 5432, "admin", "secret")

372

yaml_str = to_yaml(db_config)

373

# host: db.example.com

374

# port: 5432

375

# username: admin

376

# password: secret

377

378

db_config_copy = from_yaml(DatabaseConfig, yaml_str)

379

```

380

381

### MessagePack Example

382

383

```python

384

from serde import serde

385

from serde.msgpack import to_msgpack, from_msgpack

386

387

@serde

388

class Sensor:

389

id: int

390

temperature: float

391

humidity: float

392

timestamp: int

393

394

sensor = Sensor(1, 23.5, 45.0, 1640995200)

395

msgpack_data = to_msgpack(sensor) # Binary data

396

sensor_copy = from_msgpack(Sensor, msgpack_data)

397

```

398

399

### Multiple Format Support

400

401

```python

402

from serde import serde

403

from serde.json import to_json, from_json

404

from serde.yaml import to_yaml, from_yaml

405

from serde.toml import to_toml, from_toml

406

407

@serde

408

class AppConfig:

409

name: str

410

version: str

411

settings: dict

412

413

config = AppConfig("MyApp", "1.0.0", {"debug": True})

414

415

# Same object can be serialized to multiple formats

416

json_data = to_json(config)

417

yaml_data = to_yaml(config)

418

toml_data = to_toml(config)

419

420

# And deserialized from any format

421

config_from_json = from_json(AppConfig, json_data)

422

config_from_yaml = from_yaml(AppConfig, yaml_data)

423

config_from_toml = from_toml(AppConfig, toml_data)

424

```