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.boolean(raw: str) → Bool

Turn true or false into a boolean item.

tomlkit.comment(string: str) → Comment

Create a comment item.

tomlkit.date(raw: str) → Date

Create a TOML date.

tomlkit.datetime(raw: str) → DateTime

Create a TOML datetime.

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.float_(raw: str | float) → Float

Create an float item from a number or 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.integer(raw: str | int) → Integer

Create an integer item from a number or string.

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 ConvertError.

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/or multiline=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.time(raw: str) → Time

Create a TOML time.

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() → Container

Return a shallow copy of the dict.

classmethod fromkeys(iterable, 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.
item(key: Key | str) → Item

Get an item for the given key.

items() → a set-like object providing a view on D's items
keys() → a set-like object providing a view on D's keys
last_item() → Item | None

Get the last item.

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.

remove(key: Key | str) → Container

Remove a key from the container.

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.keys(): 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(*values)

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

comment(comment: str) → Item

Attach a comment to this item

indent(indent: int) → Item

Indent this item with given number of spaces

property trivia: Trivia

The trivia element associated with this item

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

concat(other: Key) → DottedKey

Concatenate keys into a dotted key

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(*values)

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(*values)

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.

append(key: Key | str | None, _item: Any) → Table

Appends a (key, item) to the table.

as_string() → str

The TOML representation

indent(indent: int) → Table

Indent the table with given number of spaces.

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.

raw_append(key: Key | str | None, _item: Any) → Table

Similar to append() but does not copy indentation.

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).

class tomlkit.items.Whitespace(s: str, fixed: bool = False)

Bases: Item

A whitespace literal.

as_string() → str

The TOML representation

is_fixed() → bool

If the whitespace is fixed, it can’t be merged or discarded from the output.

property trivia: Trivia

The trivia element associated with this item

property value: str

The wrapped string of the whitespace

TOML Exceptions

exception tomlkit.exceptions.ConvertError

Bases: TypeError, ValueError, TOMLKitError

Raised when item() fails to convert a value. It should be a TypeError, but due to historical reasons it needs to subclass ValueError as well.

exception tomlkit.exceptions.EmptyKeyError(line: int, col: int)

Bases: ParseError

An empty key was found during parsing.

exception tomlkit.exceptions.EmptyTableNameError(line: int, col: int)

Bases: ParseError

An empty table name was found during parsing.

exception tomlkit.exceptions.InternalParserError(line: int, col: int, message: str | None = None)

Bases: ParseError

An error that indicates a bug in the parser.

exception tomlkit.exceptions.InvalidCharInStringError(line: int, col: int, char: str)

Bases: ParseError

The string being parsed contains an invalid character.

exception tomlkit.exceptions.InvalidControlChar(line: int, col: int, char: int, type: str)

Bases: ParseError

exception tomlkit.exceptions.InvalidDateError(line: int, col: int)

Bases: ParseError

A date field was improperly specified.

exception tomlkit.exceptions.InvalidDateTimeError(line: int, col: int)

Bases: ParseError

A datetime field was improperly specified.

exception tomlkit.exceptions.InvalidNumberError(line: int, col: int)

Bases: ParseError

A numeric field was improperly specified.

exception tomlkit.exceptions.InvalidNumberOrDateError(line: int, col: int)

Bases: ParseError

A numeric or date field was improperly specified.

exception tomlkit.exceptions.InvalidStringError(value: str, invalid_sequences: Collection[str], delimiter: str)

Bases: ValueError, TOMLKitError

exception tomlkit.exceptions.InvalidTimeError(line: int, col: int)

Bases: ParseError

A date field was improperly specified.

exception tomlkit.exceptions.InvalidUnicodeValueError(line: int, col: int)

Bases: ParseError

A unicode code was improperly specified.

exception tomlkit.exceptions.KeyAlreadyPresent(key)

Bases: TOMLKitError

An already present key was used.

exception tomlkit.exceptions.MixedArrayTypesError(line: int, col: int)

Bases: ParseError

An array was found that had two or more element types.

exception tomlkit.exceptions.NonExistentKey(key)

Bases: KeyError, TOMLKitError

A non-existent key was used.

exception tomlkit.exceptions.ParseError(line: int, col: int, message: str | None = None)

Bases: ValueError, TOMLKitError

This error occurs when the parser encounters a syntax error in the TOML being parsed. The error references the line and location within the line where the error was encountered.

exception tomlkit.exceptions.TOMLKitError

Bases: Exception

exception tomlkit.exceptions.UnexpectedCharError(line: int, col: int, char: str)

Bases: ParseError

An unexpected character was found during parsing.

exception tomlkit.exceptions.UnexpectedEofError(line: int, col: int)

Bases: ParseError

The TOML being parsed ended before the end of a statement.