|
1 | 1 | from __future__ import annotations |
2 | 2 |
|
| 3 | +import contextlib |
3 | 4 | import datetime as _datetime |
4 | 5 |
|
5 | 6 | from collections.abc import Mapping |
6 | 7 | from typing import IO |
7 | 8 | from typing import Iterable |
| 9 | +from typing import TypeVar |
8 | 10 |
|
9 | 11 | from tomlkit._utils import parse_rfc3339 |
10 | 12 | from tomlkit.container import Container |
11 | 13 | from tomlkit.exceptions import UnexpectedCharError |
| 14 | +from tomlkit.items import CUSTOM_ENCODERS |
12 | 15 | from tomlkit.items import AoT |
13 | 16 | from tomlkit.items import Array |
14 | 17 | from tomlkit.items import Bool |
15 | 18 | from tomlkit.items import Comment |
16 | 19 | from tomlkit.items import Date |
17 | 20 | from tomlkit.items import DateTime |
18 | 21 | from tomlkit.items import DottedKey |
| 22 | +from tomlkit.items import Encoder |
19 | 23 | from tomlkit.items import Float |
20 | 24 | from tomlkit.items import InlineTable |
21 | 25 | from tomlkit.items import Integer |
@@ -284,3 +288,21 @@ def nl() -> Whitespace: |
284 | 288 | def comment(string: str) -> Comment: |
285 | 289 | """Create a comment item.""" |
286 | 290 | return Comment(Trivia(comment_ws=" ", comment="# " + string)) |
| 291 | + |
| 292 | + |
| 293 | +E = TypeVar("E", bound=Encoder) |
| 294 | + |
| 295 | + |
| 296 | +def register_encoder(encoder: E) -> E: |
| 297 | + """Add a custom encoder, which should be a function that will be called |
| 298 | + if the value can't otherwise be converted. It should takes a single value |
| 299 | + and return a TOMLKit item or raise a ``TypeError``. |
| 300 | + """ |
| 301 | + CUSTOM_ENCODERS.append(encoder) |
| 302 | + return encoder |
| 303 | + |
| 304 | + |
| 305 | +def unregister_encoder(encoder: Encoder) -> None: |
| 306 | + """Unregister a custom encoder.""" |
| 307 | + with contextlib.suppress(ValueError): |
| 308 | + CUSTOM_ENCODERS.remove(encoder) |
0 commit comments