0
# Dumping Functions
1
2
Functions for serializing Python objects to YAML with different safety levels and formatting options. These functions convert Python data structures to YAML strings or write them to streams.
3
4
## Capabilities
5
6
### Safe Dumping
7
8
Recommended functions for dumping Python objects to YAML. These functions use SafeRepresenter and only serialize standard Python types.
9
10
```python { .api }
11
def safe_dump(
12
data: Any,
13
stream: IO[str] | None = None,
14
*,
15
default_style: str | None = None,
16
default_flow_style: bool | None = None,
17
canonical: bool | None = None,
18
indent: int | None = None,
19
width: int | None = None,
20
allow_unicode: bool | None = None,
21
line_break: str | None = None,
22
encoding: str | None = None,
23
explicit_start: bool | None = None,
24
explicit_end: bool | None = None,
25
version: tuple[int, int] | None = None,
26
tags: dict[str, str] | None = None,
27
sort_keys: bool = True
28
) -> str | None:
29
"""
30
Serialize a Python object to YAML using SafeDumper.
31
32
Parameters:
33
- data: Python object to serialize
34
- stream: Output stream (if None, returns string)
35
- default_style: Default scalar style (None, '', '"', "'", '|', '>')
36
- default_flow_style: Use flow style for collections (True/False/None)
37
- canonical: Produce canonical YAML
38
- indent: Number of spaces for indentation (default: 2)
39
- width: Maximum line width (default: 80)
40
- allow_unicode: Allow unicode characters in output
41
- line_break: Line break character ('\n', '\r\n', '\r')
42
- encoding: Output encoding (for streams)
43
- explicit_start: Add explicit document start marker (---)
44
- explicit_end: Add explicit document end marker (...)
45
- version: YAML version tuple
46
- tags: Tag handle mappings
47
- sort_keys: Sort mapping keys alphabetically
48
49
Returns:
50
- YAML string if stream is None, otherwise None
51
52
Raises:
53
- YAMLError: If serialization fails
54
"""
55
56
def safe_dump_all(
57
documents: Sequence[Any],
58
stream: IO[str] | None = None,
59
*,
60
default_style: str | None = None,
61
default_flow_style: bool | None = None,
62
canonical: bool | None = None,
63
indent: int | None = None,
64
width: int | None = None,
65
allow_unicode: bool | None = None,
66
line_break: str | None = None,
67
encoding: str | None = None,
68
explicit_start: bool | None = None,
69
explicit_end: bool | None = None,
70
version: tuple[int, int] | None = None,
71
tags: dict[str, str] | None = None,
72
sort_keys: bool = True
73
) -> str | None:
74
"""
75
Serialize multiple Python objects to YAML using SafeDumper.
76
77
Parameters:
78
- documents: Sequence of Python objects to serialize
79
- (other parameters same as safe_dump)
80
81
Returns:
82
- YAML string with multiple documents if stream is None, otherwise None
83
84
Raises:
85
- YAMLError: If serialization fails
86
"""
87
```
88
89
### Generic Dumping
90
91
Configurable dumping functions that accept custom Dumper classes for advanced use cases.
92
93
```python { .api }
94
def dump(
95
data: Any,
96
stream: IO[str] | None = None,
97
Dumper=None,
98
*,
99
default_style: str | None = None,
100
default_flow_style: bool | None = None,
101
canonical: bool | None = None,
102
indent: int | None = None,
103
width: int | None = None,
104
allow_unicode: bool | None = None,
105
line_break: str | None = None,
106
encoding: str | None = None,
107
explicit_start: bool | None = None,
108
explicit_end: bool | None = None,
109
version: tuple[int, int] | None = None,
110
tags: dict[str, str] | None = None,
111
sort_keys: bool = True
112
) -> str | None:
113
"""
114
Serialize a Python object to YAML using specified Dumper.
115
116
Parameters:
117
- data: Python object to serialize
118
- stream: Output stream (if None, returns string)
119
- Dumper: Dumper class to use (defaults to SafeDumper)
120
- (other parameters same as safe_dump)
121
122
Returns:
123
- YAML string if stream is None, otherwise None
124
125
Raises:
126
- YAMLError: If serialization fails
127
"""
128
129
def dump_all(
130
documents: Sequence[Any],
131
stream: IO[str] | None = None,
132
Dumper=None,
133
*,
134
default_style: str | None = None,
135
default_flow_style: bool | None = None,
136
canonical: bool | None = None,
137
indent: int | None = None,
138
width: int | None = None,
139
allow_unicode: bool | None = None,
140
line_break: str | None = None,
141
encoding: str | None = None,
142
explicit_start: bool | None = None,
143
explicit_end: bool | None = None,
144
version: tuple[int, int] | None = None,
145
tags: dict[str, str] | None = None,
146
sort_keys: bool = True
147
) -> str | None:
148
"""
149
Serialize multiple Python objects to YAML using specified Dumper.
150
151
Parameters:
152
- documents: Sequence of Python objects to serialize
153
- stream: Output stream (if None, returns string)
154
- Dumper: Dumper class to use (defaults to SafeDumper)
155
- (other parameters same as safe_dump)
156
157
Returns:
158
- YAML string with multiple documents if stream is None, otherwise None
159
160
Raises:
161
- YAMLError: If serialization fails
162
"""
163
```
164
165
## Usage Examples
166
167
### Basic Dumping
168
169
```python
170
import yaml
171
172
data = {
173
'name': 'John Doe',
174
'age': 30,
175
'skills': ['Python', 'YAML', 'Docker'],
176
'active': True,
177
'score': 95.5
178
}
179
180
# Dump to string
181
yaml_string = yaml.safe_dump(data)
182
print(yaml_string)
183
# Output:
184
# age: 30
185
# active: true
186
# name: John Doe
187
# score: 95.5
188
# skills:
189
# - Python
190
# - YAML
191
# - Docker
192
193
# Dump to file
194
with open('output.yaml', 'w') as file:
195
yaml.safe_dump(data, file)
196
```
197
198
### Formatting Options
199
200
```python
201
import yaml
202
203
data = {'items': [1, 2, 3], 'nested': {'key': 'value'}}
204
205
# Block style (default)
206
block_yaml = yaml.safe_dump(data, default_flow_style=False)
207
print(block_yaml)
208
# items:
209
# - 1
210
# - 2
211
# - 3
212
# nested:
213
# key: value
214
215
# Flow style
216
flow_yaml = yaml.safe_dump(data, default_flow_style=True)
217
print(flow_yaml)
218
# {items: [1, 2, 3], nested: {key: value}}
219
220
# Custom indentation
221
custom_yaml = yaml.safe_dump(data, indent=4, default_flow_style=False)
222
print(custom_yaml)
223
# items:
224
# - 1
225
# - 2
226
# - 3
227
# nested:
228
# key: value
229
```
230
231
### Multiple Documents
232
233
```python
234
import yaml
235
236
documents = [
237
{'name': 'Document 1', 'type': 'config'},
238
{'name': 'Document 2', 'type': 'data'},
239
{'name': 'Document 3', 'type': 'settings'}
240
]
241
242
# Dump multiple documents
243
yaml_string = yaml.safe_dump_all(documents)
244
print(yaml_string)
245
# name: Document 1
246
# type: config
247
# ---
248
# name: Document 2
249
# type: data
250
# ---
251
# name: Document 3
252
# type: settings
253
```
254
255
### Advanced Formatting
256
257
```python
258
import yaml
259
260
data = {
261
'config': {
262
'database': {
263
'host': 'localhost',
264
'port': 5432,
265
'credentials': {
266
'username': 'user',
267
'password': 'secret'
268
}
269
}
270
}
271
}
272
273
yaml_string = yaml.safe_dump(
274
data,
275
default_flow_style=False,
276
indent=2,
277
width=120,
278
allow_unicode=True,
279
explicit_start=True,
280
sort_keys=False
281
)
282
print(yaml_string)
283
# ---
284
# config:
285
# database:
286
# host: localhost
287
# port: 5432
288
# credentials:
289
# username: user
290
# password: secret
291
```
292
293
### Custom Dumper
294
295
```python
296
import yaml
297
298
# Using a specific dumper
299
yaml_string = yaml.dump(data, Dumper=yaml.SafeDumper)
300
301
# Equivalent to safe_dump
302
yaml_string = yaml.safe_dump(data)
303
```
304
305
### Scalar Styles
306
307
```python
308
import yaml
309
310
# Different scalar styles for strings
311
data = {
312
'literal': 'This is a\nmultiline\nstring',
313
'folded': 'This is a long string that should be folded',
314
'quoted': 'String with "quotes" inside'
315
}
316
317
# Let PyYAML choose styles automatically
318
auto_yaml = yaml.safe_dump(data)
319
320
# Force specific styles (requires custom representer)
321
# literal: |
322
# This is a
323
# multiline
324
# string
325
# folded: >
326
# This is a long string
327
# that should be folded
328
# quoted: "String with \"quotes\" inside"
329
```