Serialize an object as YAML. Parameters ---------- obj : Any The object to serialize. enc_hook : callable, optional A callable to call for objects that aren't supported msgspec types. Takes the unsupported object and should return a supported object, or
(
obj: Any,
*,
enc_hook: Optional[Callable[[Any], Any]] = None,
order: Literal[None, "deterministic", "sorted"] = None,
)
| 37 | |
| 38 | |
| 39 | def encode( |
| 40 | obj: Any, |
| 41 | *, |
| 42 | enc_hook: Optional[Callable[[Any], Any]] = None, |
| 43 | order: Literal[None, "deterministic", "sorted"] = None, |
| 44 | ) -> bytes: |
| 45 | """Serialize an object as YAML. |
| 46 | |
| 47 | Parameters |
| 48 | ---------- |
| 49 | obj : Any |
| 50 | The object to serialize. |
| 51 | enc_hook : callable, optional |
| 52 | A callable to call for objects that aren't supported msgspec types. |
| 53 | Takes the unsupported object and should return a supported object, or |
| 54 | raise a ``NotImplementedError`` if unsupported. |
| 55 | order : {None, 'deterministic', 'sorted'}, optional |
| 56 | The ordering to use when encoding unordered compound types. |
| 57 | |
| 58 | - ``None``: All objects are encoded in the most efficient manner |
| 59 | matching their in-memory representations. The default. |
| 60 | - `'deterministic'`: Dict keys and set elements are sorted so that |
| 61 | values which compare equal produce identical encoded output, |
| 62 | regardless of insertion or iteration order. Useful when |
| 63 | comparison/hashing of the encoded binary output is necessary. |
| 64 | - `'sorted'`: Like `'deterministic'`, but *all* object-like types |
| 65 | (structs, dataclasses, ...) are also sorted by field name before |
| 66 | encoding. This is slower than `'deterministic'`, but may produce more |
| 67 | human-readable output. |
| 68 | |
| 69 | Returns |
| 70 | ------- |
| 71 | data : bytes |
| 72 | The serialized object. |
| 73 | |
| 74 | Notes |
| 75 | ----- |
| 76 | This function requires that the third-party `PyYAML library |
| 77 | <https://pyyaml.org/>`_ is installed. |
| 78 | |
| 79 | See Also |
| 80 | -------- |
| 81 | decode |
| 82 | """ |
| 83 | yaml = _import_pyyaml("encode") |
| 84 | # Use the C extension if available |
| 85 | Dumper = getattr(yaml, "CSafeDumper", yaml.SafeDumper) |
| 86 | |
| 87 | return yaml.dump_all( |
| 88 | [ |
| 89 | _to_builtins( |
| 90 | obj, |
| 91 | builtin_types=(_datetime.datetime, _datetime.date), |
| 92 | enc_hook=enc_hook, |
| 93 | order=order, |
| 94 | ) |
| 95 | ], |
| 96 | encoding="utf-8", |
nothing calls this directly
no test coverage detected
searching dependent graphs…