or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/pypi-pyserde

Yet another serialization library on top of dataclasses

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/pyserde@0.25.x

To install, run

npx @tessl/cli install tessl/pypi-pyserde@0.25.0

0

# pyserde

1

2

A comprehensive Python serialization library built on dataclasses that enables automatic conversion of Python objects to and from multiple data formats including JSON, YAML, TOML, MessagePack, and Pickle. Inspired by Rust's serde, it provides a decorator-based approach with extensive type system support and high-performance serialization.

3

4

## Package Information

5

6

- **Package Name**: pyserde

7

- **Language**: Python

8

- **Installation**: `pip install pyserde`

9

- **Optional dependencies**: `pip install pyserde[all]` for all formats

10

11

## Core Imports

12

13

```python

14

from serde import serde, to_dict, from_dict, to_json, from_json

15

```

16

17

Format-specific imports:

18

```python

19

from serde.json import to_json, from_json

20

from serde.yaml import to_yaml, from_yaml

21

from serde.toml import to_toml, from_toml

22

from serde.msgpack import to_msgpack, from_msgpack

23

from serde.pickle import to_pickle, from_pickle

24

```

25

26

## Basic Usage

27

28

```python

29

from serde import serde, to_dict, from_dict

30

from serde.json import to_json, from_json

31

32

@serde

33

class Person:

34

name: str

35

age: int

36

email: str | None = None

37

38

# Create an instance

39

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

40

41

# Serialize to JSON

42

json_data = to_json(person)

43

# '{"name":"Alice","age":30,"email":"alice@example.com"}'

44

45

# Deserialize from JSON

46

person_copy = from_json(Person, json_data)

47

# Person(name='Alice', age=30, email='alice@example.com')

48

49

# Serialize to dictionary

50

dict_data = to_dict(person)

51

# {'name': 'Alice', 'age': 30, 'email': 'alice@example.com'}

52

53

# Deserialize from dictionary

54

person_from_dict = from_dict(Person, dict_data)

55

```

56

57

## Architecture

58

59

pyserde uses a code generation approach for high performance:

60

61

- **@serde decorator**: Analyzes dataclass fields and generates specialized serialization/deserialization functions

62

- **Type introspection**: Leverages Python's type hints for automatic (de)serialization logic

63

- **Format abstraction**: Common serialization core with pluggable format-specific backends

64

- **Scope management**: Generated code is cached and managed efficiently for performance

65

66

## Capabilities

67

68

### Core Serialization

69

70

The fundamental serialization and deserialization functionality that powers all format-specific modules. Provides the @serde decorator and core conversion functions.

71

72

```python { .api }

73

def serde(

74

_cls: Any = None,

75

rename_all: Optional[str] = None,

76

reuse_instances_default: bool = True,

77

convert_sets_default: bool = False,

78

serializer: Optional[SerializeFunc] = None,

79

deserializer: Optional[DeserializeFunc] = None,

80

tagging: Tagging = DefaultTagging,

81

type_check: TypeCheck = strict,

82

serialize_class_var: bool = False,

83

class_serializer: Optional[ClassSerializer] = None,

84

class_deserializer: Optional[ClassDeserializer] = None,

85

deny_unknown_fields: bool = False,

86

) -> Any: ...

87

88

def to_dict(

89

o: Any,

90

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

91

reuse_instances: Optional[bool] = None,

92

convert_sets: Optional[bool] = None,

93

skip_none: bool = False,

94

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

95

96

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

97

98

def to_tuple(

99

o: Any,

100

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

101

reuse_instances: Optional[bool] = None,

102

convert_sets: Optional[bool] = None,

103

skip_none: bool = False,

104

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

105

106

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

107

```

108

109

[Core Serialization](./core-serialization.md)

110

111

### Format-Specific Modules

112

113

Serialization and deserialization functions for specific data formats including JSON, YAML, TOML, MessagePack, and Pickle.

114

115

```python { .api }

116

# JSON

117

def to_json(

118

obj: Any,

119

cls: Optional[Any] = None,

120

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

121

reuse_instances: bool = False,

122

convert_sets: bool = True,

123

skip_none: bool = False,

124

**opts: Any

125

) -> str: ...

126

127

def from_json(

128

c: type[T],

129

s: AnyStr,

130

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

131

**opts: Any

132

) -> T: ...

133

134

# YAML

135

def to_yaml(

136

obj: Any,

137

cls: Optional[Any] = None,

138

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

139

reuse_instances: bool = False,

140

convert_sets: bool = True,

141

skip_none: bool = False,

142

**opts: Any,

143

) -> str: ...

144

145

def from_yaml(

146

c: type[T],

147

s: str,

148

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

149

**opts: Any

150

) -> T: ...

151

152

# TOML

153

def to_toml(

154

obj: Any,

155

cls: Optional[Any] = None,

156

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

157

reuse_instances: bool = False,

158

convert_sets: bool = True,

159

skip_none: bool = True,

160

**opts: Any,

161

) -> str: ...

162

163

def from_toml(

164

c: type[T],

165

s: str,

166

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

167

**opts: Any

168

) -> T: ...

169

```

170

171

[Format Modules](./format-modules.md)

172

173

### Field Configuration and Customization

174

175

Advanced field-level configuration for custom serialization behavior, field renaming, skipping, and custom serializers.

176

177

```python { .api }

178

def field(

179

default=...,

180

default_factory=...,

181

init: bool = True,

182

repr: bool = True,

183

hash: bool | None = None,

184

compare: bool = True,

185

metadata: dict | None = None,

186

rename: str | None = None,

187

serializer: Callable | None = None,

188

deserializer: Callable | None = None,

189

flatten: bool = False,

190

skip: bool = False,

191

skip_if: Callable | None = None,

192

skip_if_false: bool = False,

193

skip_if_default: bool = False,

194

) -> Any: ...

195

```

196

197

[Field Configuration](./field-configuration.md)

198

199

### Union Handling and Type Checking

200

201

Advanced type system features including union type handling with different tagging strategies and configurable type checking modes.

202

203

```python { .api }

204

# Tagging strategies

205

class ExternalTagging: ...

206

class InternalTagging: ...

207

class AdjacentTagging: ...

208

class Untagged: ...

209

210

# Type checking modes

211

class TypeCheck: ...

212

strict: TypeCheck

213

disabled: TypeCheck

214

coerce: TypeCheck

215

```

216

217

[Union Handling](./union-handling.md)

218

219

### Type System Compatibility

220

221

Comprehensive type introspection and compatibility utilities for working with Python's type system, generics, and complex nested types.

222

223

```python { .api }

224

def is_union(typ) -> bool: ...

225

def is_opt(typ) -> bool: ...

226

def is_list(typ) -> bool: ...

227

def is_dict(typ) -> bool: ...

228

def get_origin(typ): ...

229

def get_args(typ): ...

230

```

231

232

[Type System](./type-system.md)

233

234

### Inspection and Debugging

235

236

Tools for debugging and inspecting generated serialization code.

237

238

```python { .api }

239

def inspect(cls: type[Any]) -> None:

240

"""

241

Inspect a pyserde class and print generated code.

242

243

Parameters:

244

- cls: Pyserde-decorated class to inspect

245

"""

246

```

247

248

## Types

249

250

```python { .api }

251

from typing import TypeVar, Protocol, Callable, Any

252

253

T = TypeVar('T')

254

255

class SerializeFunc(Protocol):

256

def __call__(self, obj: Any) -> Any: ...

257

258

class DeserializeFunc(Protocol):

259

def __call__(self, cls: type, obj: Any) -> Any: ...

260

261

class ClassSerializer(Protocol):

262

def serialize(self, obj: Any) -> Any: ...

263

264

class ClassDeserializer(Protocol):

265

def deserialize(self, cls: type, data: Any) -> Any: ...

266

267

class Tagging:

268

"""Base class for union tagging strategies."""

269

270

class TypeCheck:

271

"""Type checking configuration."""

272

273

class SerdeError(Exception):

274

"""Base exception for serde errors."""

275

276

class SerdeSkip(Exception):

277

"""Exception to skip field serialization."""

278

```