Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/tomlkit/api.py: 50%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1from __future__ import annotations
3import contextlib
4import datetime as _datetime
5import re
7from collections.abc import Iterable
8from collections.abc import Mapping
9from typing import IO
10from typing import TYPE_CHECKING
11from typing import Any
12from typing import TypeVar
14from tomlkit._utils import parse_rfc3339
15from tomlkit._utils import validate_comment
16from tomlkit.container import Container
17from tomlkit.exceptions import UnexpectedCharError
18from tomlkit.items import CUSTOM_ENCODERS
19from tomlkit.items import AoT
20from tomlkit.items import Array
21from tomlkit.items import Bool
22from tomlkit.items import Comment
23from tomlkit.items import Date
24from tomlkit.items import DateTime
25from tomlkit.items import DottedKey
26from tomlkit.items import Float
27from tomlkit.items import InlineTable
28from tomlkit.items import Integer
29from tomlkit.items import Item as _Item
30from tomlkit.items import Key
31from tomlkit.items import SingleKey
32from tomlkit.items import String
33from tomlkit.items import StringType as _StringType
34from tomlkit.items import Table
35from tomlkit.items import Time
36from tomlkit.items import Trivia
37from tomlkit.items import Whitespace
38from tomlkit.items import item as item
39from tomlkit.parser import Parser
40from tomlkit.toml_document import TOMLDocument as TOMLDocument
43if TYPE_CHECKING:
44 from tomlkit.items import Encoder
46 E = TypeVar("E", bound=Encoder)
49def loads(string: str | bytes) -> TOMLDocument:
50 """
51 Parses a string into a TOMLDocument.
53 Alias for parse().
54 """
55 return parse(string)
58def dumps(data: Mapping[str, Any], sort_keys: bool = False) -> str:
59 """
60 Dumps a TOMLDocument into a string.
61 """
62 if isinstance(data, (Table, InlineTable, Container)):
63 if not sort_keys:
64 return data.as_string()
66 return item(data, _sort_keys=True).as_string()
68 if isinstance(data, Mapping):
69 return item(dict(data), _sort_keys=sort_keys).as_string()
71 try:
72 # mapping-like wrappers (e.g. dotty_dict's Dotty) delegate
73 # ``as_string`` to the document they wrap; rendering it directly
74 # preserves the original layout, which re-encoding through a plain
75 # dict would lose
76 return data.as_string() # type: ignore[attr-defined]
77 except AttributeError as ex:
78 msg = f"Expecting Mapping or TOML Table or Container, {type(data)} given"
79 raise TypeError(msg) from ex
82def load(fp: IO[str] | IO[bytes]) -> TOMLDocument:
83 """
84 Load toml document from a file-like object.
85 """
86 return parse(fp.read())
89def dump(data: Mapping[str, Any], fp: IO[str], *, sort_keys: bool = False) -> None:
90 """
91 Dump a TOMLDocument into a writable file stream.
93 :param data: a dict-like object to dump
94 :param sort_keys: if true, sort the keys in alphabetic order
96 :Example:
98 >>> with open("output.toml", "w") as fp:
99 ... tomlkit.dump(data, fp)
100 """
101 fp.write(dumps(data, sort_keys=sort_keys))
104def parse(string: str | bytes) -> TOMLDocument:
105 """
106 Parses a string or bytes into a TOMLDocument.
107 """
108 return Parser(string).parse()
111def document() -> TOMLDocument:
112 """
113 Returns a new TOMLDocument instance.
114 """
115 return TOMLDocument()
118# Items
119_INTEGER_RE = re.compile(
120 r"(?:"
121 r"0x[0-9a-fA-F](?:_?[0-9a-fA-F])*" # hex: lowercase prefix only, no sign
122 r"|0o[0-7](?:_?[0-7])*" # octal: lowercase prefix only, no sign
123 r"|0b[01](?:_?[01])*" # binary: lowercase prefix only, no sign
124 r"|[+-]?(?:0|[1-9](?:_?[0-9])*)" # decimal: optional sign, no leading zeros
125 r")"
126)
127"""Valid TOML v1.0.0 integer literals (https://toml.io/en/v1.0.0#integer).
129Underscores may only appear between digits; hex/octal/binary use a
130lowercase prefix and take no sign, mirroring ``Parser._parse_number``.
131"""
134def integer(raw: str | int) -> Integer:
135 """Create an integer item from a number or string.
137 When ``raw`` is a string it must be a valid TOML v1.0.0 integer
138 literal; the original text is then preserved verbatim so grouping
139 underscores (e.g. ``"1_000"``) survive ``dumps()``. Anything else
140 raises ``ValueError``.
141 """
142 if isinstance(raw, str):
143 if not _INTEGER_RE.fullmatch(raw):
144 raise ValueError(f"Invalid TOML integer: {raw!r}")
145 return Integer(int(raw, 0), Trivia(), raw)
146 return item(int(raw))
149def float_(raw: str | float) -> Float:
150 """Create an float item from a number or string."""
151 return item(float(raw))
154def boolean(raw: str | bool) -> Bool:
155 """Turn `true` or `false` into a boolean item."""
156 return item(raw == "true" if isinstance(raw, str) else raw)
159def string(
160 raw: str,
161 *,
162 literal: bool = False,
163 multiline: bool = False,
164 escape: bool = True,
165) -> String:
166 """Create a string item.
168 By default, this function will create *single line basic* strings, but
169 boolean flags (e.g. ``literal=True`` and/or ``multiline=True``)
170 can be used for personalization.
172 For more information, please check the spec: `<https://toml.io/en/v1.0.0#string>`__.
174 Dumping produces a TOML string that faithfully represents the given string.
175 This includes character escaping for basic strings.
176 This behaviour can be disabled by setting ``escape=False``.
177 In that case, the given string is used verbatim for the content of the TOML string.
178 Please note that this makes you responsible for ensuring the given string does not
179 contain any forbidden character or sequence.
180 """
181 type_ = _StringType.select(literal, multiline)
182 return String.from_raw(raw, type_, escape)
185def date(raw: str) -> Date:
186 """Create a TOML date."""
187 value = parse_rfc3339(raw)
188 if isinstance(value, _datetime.datetime) or not isinstance(value, _datetime.date):
189 raise ValueError("date() only accepts date strings.")
191 return item(value)
194def time(raw: str) -> Time:
195 """Create a TOML time."""
196 value = parse_rfc3339(raw)
197 if not isinstance(value, _datetime.time):
198 raise ValueError("time() only accepts time strings.")
200 return item(value)
203def datetime(raw: str) -> DateTime:
204 """Create a TOML datetime."""
205 value = parse_rfc3339(raw)
206 if not isinstance(value, _datetime.datetime):
207 raise ValueError("datetime() only accepts datetime strings.")
209 return item(value)
212def array(raw: str = "[]") -> Array:
213 """Create an array item for its string representation.
215 :Example:
217 >>> array("[1, 2, 3]") # Create from a string
218 [1, 2, 3]
219 >>> a = array()
220 >>> a.extend([1, 2, 3]) # Create from a list
221 >>> a
222 [1, 2, 3]
223 """
224 v = value(raw)
225 if not isinstance(v, Array):
226 raise ValueError(f"Expected an array, got {type(v)}")
227 return v
230def table(is_super_table: bool | None = None) -> Table:
231 """Create an empty table.
233 :param is_super_table: if true, the table is a super table
235 :Example:
237 >>> doc = document()
238 >>> foo = table(True)
239 >>> bar = table()
240 >>> bar.update({'x': 1})
241 >>> foo.append('bar', bar)
242 >>> doc.append('foo', foo)
243 >>> print(doc.as_string())
244 [foo.bar]
245 x = 1
246 """
247 return Table(Container(), Trivia(), False, is_super_table)
250def inline_table() -> InlineTable:
251 """Create an inline table.
253 :Example:
255 >>> table = inline_table()
256 >>> table.update({'x': 1, 'y': 2})
257 >>> print(table.as_string())
258 {x = 1, y = 2}
259 """
260 return InlineTable(Container(), Trivia(), new=True)
263def aot() -> AoT:
264 """Create an array of table.
266 :Example:
268 >>> doc = document()
269 >>> aot = aot()
270 >>> aot.append(item({'x': 1}))
271 >>> doc.append('foo', aot)
272 >>> print(doc.as_string())
273 [[foo]]
274 x = 1
275 """
276 return AoT([])
279def key(k: str | Iterable[str]) -> Key:
280 """Create a key from a string. When a list of string is given,
281 it will create a dotted key.
283 :Example:
285 >>> doc = document()
286 >>> doc.append(key('foo'), 1)
287 >>> doc.append(key(['bar', 'baz']), 2)
288 >>> print(doc.as_string())
289 foo = 1
290 bar.baz = 2
291 """
292 if isinstance(k, str):
293 return SingleKey(k)
294 keys = [SingleKey(_k) for _k in k]
295 if len(keys) == 1:
296 return keys[0]
297 return DottedKey(keys)
300def value(raw: str) -> _Item:
301 """Parse a simple value from a string.
303 :Example:
305 >>> value("1")
306 1
307 >>> value("true")
308 True
309 >>> value("[1, 2, 3]")
310 [1, 2, 3]
311 """
312 parser = Parser(raw)
313 v = parser._parse_value()
314 if not parser.end():
315 raise parser.parse_error(UnexpectedCharError, char=parser._current)
316 return v
319def key_value(src: str) -> tuple[Key, _Item]:
320 """Parse a key-value pair from a string.
322 Anything other than whitespace or a comment after the pair is an error,
323 as it is when the same text is given to :func:`parse`.
325 :Example:
327 >>> key_value("foo = 1")
328 (Key('foo'), 1)
329 """
330 parser = Parser(src)
331 k, v = parser._parse_key_value(parse_comment=True)
332 if not parser.end():
333 raise parser.parse_error(UnexpectedCharError, char=parser._current)
334 return k, v
337def ws(src: str) -> Whitespace:
338 """Create a whitespace from a string."""
339 return Whitespace(src, fixed=True)
342def nl() -> Whitespace:
343 """Create a newline item."""
344 return ws("\n")
347def comment(string: str) -> Comment:
348 """Create a comment item.
350 A multiline string produces one ``#``-prefixed line per line so that the
351 result is still valid TOML.
352 """
353 validate_comment(string, multiline=True)
354 lines = string.split("\n")
355 rendered = "\n".join(f"# {line}" if line else "#" for line in lines)
356 return Comment(Trivia(comment_ws=" ", comment=rendered))
359def register_encoder(encoder: E) -> E:
360 """Add a custom encoder, which should be a function that will be called
361 if the value can't otherwise be converted.
363 The encoder should return a TOMLKit item or raise a ``ConvertError``.
365 Example::
367 @register_encoder
368 def encode_custom_dict(obj, _parent=None, _sort_keys=False):
369 if isinstance(obj, CustomDict):
370 tbl = table()
371 for key, value in obj.items():
372 # Pass along parameters when encoding nested values
373 tbl[key] = item(value, _parent=tbl, _sort_keys=_sort_keys)
374 return tbl
375 raise ConvertError("Not a CustomDict")
376 """
377 CUSTOM_ENCODERS.append(encoder)
378 return encoder
381def unregister_encoder(encoder: Encoder) -> None:
382 """Unregister a custom encoder."""
383 with contextlib.suppress(ValueError):
384 CUSTOM_ENCODERS.remove(encoder)