API Reference¶
Public API¶
Functions you need to create TOML elements to construct a TOML document.
- class tomlkit.TOMLDocument(parsed: bool = False)¶
Bases:
Container
A TOML document.
- tomlkit.aot() AoT ¶
Create an array of table.
- Example:
>>> doc = document() >>> aot = aot() >>> aot.append(item({'x': 1})) >>> doc.append('foo', aot) >>> print(doc.as_string()) [[foo]] x = 1
- tomlkit.array(raw: str = '[]') Array ¶
Create an array item for its string representation.
- Example:
>>> array("[1, 2, 3]") # Create from a string [1, 2, 3] >>> a = array() >>> a.extend([1, 2, 3]) # Create from a list >>> a [1, 2, 3]
- tomlkit.document() TOMLDocument ¶
Returns a new TOMLDocument instance.
- tomlkit.dump(data: Mapping, fp: IO[str], *, sort_keys: bool = False) None ¶
Dump a TOMLDocument into a writable file stream.
- Parameters:
data – a dict-like object to dump
sort_keys – if true, sort the keys in alphabetic order
- Example:
>>> with open("output.toml", "w") as fp: ... tomlkit.dump(data, fp)
- tomlkit.dumps(data: Mapping, sort_keys: bool = False) str ¶
Dumps a TOMLDocument into a string.
- tomlkit.inline_table() InlineTable ¶
Create an inline table.
- Example:
>>> table = inline_table() >>> table.update({'x': 1, 'y': 2}) >>> print(table.as_string()) {x = 1, y = 2}
- tomlkit.item(value: Any, _parent: Item | None = None, _sort_keys: bool = False) Item ¶
Create a TOML item from a Python object.
- Example:
>>> item(42) 42 >>> item([1, 2, 3]) [1, 2, 3] >>> item({'a': 1, 'b': 2}) a = 1 b = 2
- tomlkit.key(k: str | Iterable[str]) Key ¶
Create a key from a string. When a list of string is given, it will create a dotted key.
- Example:
>>> doc = document() >>> doc.append(key('foo'), 1) >>> doc.append(key(['bar', 'baz']), 2) >>> print(doc.as_string()) foo = 1 bar.baz = 2
- tomlkit.key_value(src: str) tuple[Key, Item] ¶
Parse a key-value pair from a string.
- Example:
>>> key_value("foo = 1") (Key('foo'), 1)
- tomlkit.load(fp: IO[str] | IO[bytes]) TOMLDocument ¶
Load toml document from a file-like object.
- tomlkit.loads(string: str | bytes) TOMLDocument ¶
Parses a string into a TOMLDocument.
Alias for parse().
- tomlkit.nl() Whitespace ¶
Create a newline item.
- tomlkit.parse(string: str | bytes) TOMLDocument ¶
Parses a string or bytes into a TOMLDocument.
- tomlkit.register_encoder(encoder: E) E ¶
Add a custom encoder, which should be a function that will be called if the value can’t otherwise be converted. It should takes a single value and return a TOMLKit item or raise a
TypeError
.
- tomlkit.string(raw: str, *, literal: bool = False, multiline: bool = False, escape: bool = True) String ¶
Create a string item.
By default, this function will create single line basic strings, but boolean flags (e.g.
literal=True
and/ormultiline=True
) can be used for personalization.For more information, please check the spec: https://toml.io/en/v1.0.0#string.
Common escaping rules will be applied for basic strings. This can be controlled by explicitly setting
escape=False
. Please note that, if you disable escaping, you will have to make sure that the given strings don’t contain any forbidden character or sequence.
- tomlkit.table(is_super_table: bool | None = None) Table ¶
Create an empty table.
- Parameters:
is_super_table – if true, the table is a super table
- Example:
>>> doc = document() >>> foo = table(True) >>> bar = table() >>> bar.update({'x': 1}) >>> foo.append('bar', bar) >>> doc.append('foo', foo) >>> print(doc.as_string()) [foo.bar] x = 1
- tomlkit.unregister_encoder(encoder: Encoder) None ¶
Unregister a custom encoder.
- tomlkit.value(raw: str) Item ¶
Parse a simple value from a string.
- Example:
>>> value("1") 1 >>> value("true") True >>> value("[1, 2, 3]") [1, 2, 3]
- tomlkit.ws(src: str) Whitespace ¶
Create a whitespace from a string.
TOML Document¶
- class tomlkit.toml_document.TOMLDocument(parsed: bool = False)¶
Bases:
Container
A TOML document.
- add(key: Key | Item | str, item: Item | None = None) Container ¶
Adds an item to the current Container.
- Example:
>>> # add a key-value pair >>> doc.add('key', 'value') >>> # add a comment or whitespace or newline >>> doc.add(comment('# comment'))
- append(key: Key | str | None, item: Item, validate: bool = True) Container ¶
Similar to
add()
but both key and value must be given.
- as_string() str ¶
Render as TOML string.
- clear() None. Remove all items from D. ¶
- copy() a shallow copy of D ¶
- fromkeys(value=None, /)¶
Create a new dictionary with keys from iterable and values set to value.
- get(k[, d]) D[k] if k in D, else d. d defaults to None. ¶
- items() a set-like object providing a view on D's items ¶
- keys() a set-like object providing a view on D's keys ¶
- pop(k[, d]) v, remove specified key and return the corresponding value. ¶
If key is not found, d is returned if given, otherwise KeyError is raised.
- popitem() (k, v), remove and return some (key, value) pair ¶
as a 2-tuple; but raise KeyError if D is empty.
- setdefault(k[, d]) D.get(k,d), also set D[k]=d if k not in D ¶
- unwrap() dict[str, Any] ¶
Returns as pure python object (ppo)
- update([E, ]**F) None. Update D from mapping/iterable E and F. ¶
If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v
- property value: dict[str, Any]¶
The wrapped dict value
- values() an object providing a view on D's values ¶
TOML File¶
- class tomlkit.toml_file.TOMLFile(path: str | PathLike)¶
Bases:
object
Represents a TOML file.
- Parameters:
path – path to the TOML file
- read() TOMLDocument ¶
Read the file content as a
tomlkit.toml_document.TOMLDocument
.
- write(data: TOMLDocument) None ¶
Write the TOMLDocument to the file.
TOML Items¶
- class tomlkit.items.AoT(body: list[Table], name: str | None = None, parsed: bool = False)¶
Bases:
Item
,_CustomList
An array of table literal
- as_string() str ¶
The TOML representation
- insert(index: int, value: dict) None ¶
S.insert(index, value) – insert value before index
- invalidate_display_name()¶
Call
invalidate_display_name
on the contained tables
- unwrap() list[dict[str, Any]] ¶
Returns as pure python object (ppo)
- class tomlkit.items.Array(value: list[Item], trivia: Trivia, multiline: bool = False)¶
Bases:
Item
,_CustomList
An array literal
- add_line(*items: Any, indent: str = ' ', comment: str | None = None, add_comma: bool = True, newline: bool = True) None ¶
Add multiple items in a line to control the format precisely. When add_comma is True, only accept actual values and “, “ will be added between values automatically.
- Example:
>>> a = array() >>> a.add_line(1, 2, 3) >>> a.add_line(4, 5, 6) >>> a.add_line(indent="") >>> print(a.as_string()) [ 1, 2, 3, 4, 5, 6, ]
- as_string() str ¶
The TOML representation
- clear() None ¶
Clear the array.
- insert(pos: int, value: Any) None ¶
S.insert(index, value) – insert value before index
- multiline(multiline: bool) Array ¶
Change the array to display in multiline or not.
- Example:
>>> a = item([1, 2, 3]) >>> print(a.as_string()) [1, 2, 3] >>> print(a.multiline(True).as_string()) [ 1, 2, 3, ]
- unwrap() list[Any] ¶
Returns as pure python object (ppo)
- class tomlkit.items.Bool(t: int, trivia: Trivia)¶
Bases:
Item
A boolean literal.
- as_string() str ¶
The TOML representation
- unwrap() bool ¶
Returns as pure python object (ppo)
- property value: bool¶
The wrapped boolean value
- class tomlkit.items.BoolType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)¶
Bases:
Enum
- class tomlkit.items.Comment(trivia: Trivia)¶
Bases:
Item
A comment literal.
- as_string() str ¶
The TOML representation
- class tomlkit.items.Date(year: int, month: int, day: int, *_: Any)¶
Bases:
Item
,date
A date literal.
- as_string() str ¶
The TOML representation
- replace(*args: Any, **kwargs: Any) date ¶
Return date with new specified fields.
- unwrap() date ¶
Returns as pure python object (ppo)
- class tomlkit.items.DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int, microsecond: int, tzinfo: tzinfo | None, *_: Any, **kwargs: Any)¶
Bases:
Item
,datetime
A datetime literal.
- as_string() str ¶
The TOML representation
- astimezone(tz: tzinfo) datetime ¶
tz -> convert to local time in new timezone tz
- replace(*args: Any, **kwargs: Any) datetime ¶
Return datetime with new specified fields.
- unwrap() datetime ¶
Returns as pure python object (ppo)
- class tomlkit.items.DottedKey(keys: Iterable[SingleKey], sep: str | None = None, original: str | None = None)¶
Bases:
Key
- class tomlkit.items.Float(value: float, trivia: Trivia, raw: str)¶
Bases:
Item
,_CustomFloat
A float literal.
- as_string() str ¶
The TOML representation
- unwrap() float ¶
Returns as pure python object (ppo)
- property value: float¶
The wrapped float value
- class tomlkit.items.InlineTable(value: container.Container, trivia: Trivia, new: bool = False)¶
Bases:
AbstractTable
An inline table literal.
- append(key: Key | str | None, _item: Any) InlineTable ¶
Appends a (key, item) to the table.
- as_string() str ¶
The TOML representation
- class tomlkit.items.Integer(value: int, trivia: Trivia, raw: str)¶
Bases:
Item
,_CustomInt
An integer literal.
- as_string() str ¶
The TOML representation
- unwrap() int ¶
Returns as pure python object (ppo)
- property value: int¶
The wrapped integer value
- class tomlkit.items.Item(trivia: Trivia)¶
Bases:
object
An item within a TOML document.
- as_string() str ¶
The TOML representation
- unwrap() Any ¶
Returns as pure python object (ppo)
- class tomlkit.items.Key¶
Bases:
ABC
Base class for a key
- as_string() str ¶
The TOML representation
- is_dotted() bool ¶
If the key is followed by other keys
- is_multi() bool ¶
Check if the key contains multiple keys
- class tomlkit.items.KeyType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)¶
Bases:
Enum
The type of a Key.
Keys can be bare (unquoted), or quoted using basic (“), or literal (‘) quotes following the same escaping rules as single-line StringType.
- class tomlkit.items.Null¶
Bases:
Item
A null item.
- as_string() str ¶
The TOML representation
- unwrap() None ¶
Returns as pure python object (ppo)
- class tomlkit.items.SingleKey(k: str, t: KeyType | None = None, sep: str | None = None, original: str | None = None)¶
Bases:
Key
A single key
- property delimiter: str¶
The delimiter: double quote/single quote/none
- is_bare() bool ¶
Check if the key is bare
- class tomlkit.items.String(t, value, original, trivia)¶
Bases:
str
,Item
A string literal.
- as_string() str ¶
The TOML representation
- unwrap() str ¶
Returns as pure python object (ppo)
- class tomlkit.items.StringType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)¶
Bases:
Enum
- class tomlkit.items.Table(value: container.Container, trivia: Trivia, is_aot_element: bool, is_super_table: bool | None = None, name: str | None = None, display_name: str | None = None)¶
Bases:
AbstractTable
A table literal.
- as_string() str ¶
The TOML representation
- invalidate_display_name()¶
Call
invalidate_display_name
on the contained tables
- is_aot_element() bool ¶
True if the table is the direct child of an AOT element.
- is_super_table() bool ¶
A super table is the intermediate parent of a nested table as in [a.b.c]. If true, it won’t appear in the TOML representation.
- class tomlkit.items.Time(hour: int, minute: int, second: int, microsecond: int, tzinfo: tzinfo | None, *_: Any)¶
Bases:
Item
,time
A time literal.
- as_string() str ¶
The TOML representation
- replace(*args: Any, **kwargs: Any) time ¶
Return time with new specified fields.
- unwrap() time ¶
Returns as pure python object (ppo)
- class tomlkit.items.Trivia(indent: str = '', comment_ws: str = '', comment: str = '', trail: str = '\n')¶
Bases:
object
Trivia information (aka metadata).