API Reference

Public API

Functions you need to create TOML elements to construct a TOML document.

class tomlkit.TOMLDocument(parsed: bool = False)

Bases: tomlkit.container.Container

A TOML document.

tomlkit.aot() tomlkit.items.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 = None) tomlkit.items.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) tomlkit.items.Bool

Turn true or false into a boolean item.

tomlkit.comment(string: str) tomlkit.items.Comment

Create a comment item.

tomlkit.date(raw: str) tomlkit.items.Date

Create a TOML date.

tomlkit.datetime(raw: str) tomlkit.items.DateTime

Create a TOML datetime.

tomlkit.document() tomlkit.toml_document.TOMLDocument

Returns a new TOMLDocument instance.

tomlkit.dump(data: collections.abc.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

tomlkit.dumps(data: collections.abc.Mapping, sort_keys: bool = False) str

Dumps a TOMLDocument into a string.

tomlkit.float_(raw: str | float) tomlkit.items.Float

Create an float item from a number or string.

tomlkit.inline_table() tomlkit.items.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) tomlkit.items.Integer

Create an integer item from a number or string.

tomlkit.item(value: Any, _parent: tomlkit.items.Item | None = None, _sort_keys: bool = False) tomlkit.items.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: Union[str, Iterable[str]]) tomlkit.items.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[tomlkit.items.Key, tomlkit.items.Item]

Parse a key-value pair from a string.

Example

>>> key_value("foo = 1")
(Key('foo'), 1)
tomlkit.load(fp: Union[IO[str], IO[bytes]]) tomlkit.toml_document.TOMLDocument

Load toml document from a file-like object.

tomlkit.loads(string: str | bytes) tomlkit.toml_document.TOMLDocument

Parses a string into a TOMLDocument.

Alias for parse().

tomlkit.nl() tomlkit.items.Whitespace

Create a newline item.

tomlkit.parse(string: str | bytes) tomlkit.toml_document.TOMLDocument

Parses a string or bytes into a TOMLDocument.

tomlkit.register_encoder(encoder: tomlkit.api.E) tomlkit.api.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) tomlkit.items.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) tomlkit.items.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) tomlkit.items.Time

Create a TOML time.

tomlkit.unregister_encoder(encoder: Encoder) None

Unregister a custom encoder.

tomlkit.value(raw: str) tomlkit.items.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) tomlkit.items.Whitespace

Create a whitespace from a string.

TOML Document

class tomlkit.toml_document.TOMLDocument(parsed: bool = False)

Bases: tomlkit.container.Container

A TOML document.

add(key: tomlkit.items.Key | tomlkit.items.Item | str, item: tomlkit.items.Item | None = None) tomlkit.container.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: tomlkit.items.Key | str | None, item: tomlkit.items.Item) tomlkit.container.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.
item(key: tomlkit.items.Key | str) tomlkit.items.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() tomlkit.items.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: tomlkit.items.Key | str) tomlkit.container.Container

Remove a key from the container.

setdefault(k[, d]) D.get(k,d), also set D[k]=d if k not in D
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

values() an object providing a view on D's values

TOML File

class tomlkit.toml_file.TOMLFile(path: Union[str, os.PathLike])

Bases: object

Represents a TOML file.

Parameters

path – path to the TOML file

read() tomlkit.toml_document.TOMLDocument

Read the file content as a tomlkit.toml_document.TOMLDocument.

write(data: tomlkit.toml_document.TOMLDocument) None

Write the TOMLDocument to the file.

TOML Items

class tomlkit.items.AoT(body: list[tomlkit.items.Table], name: str | None = None, parsed: bool = False)

Bases: tomlkit.items.Item, tomlkit._types._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, typing.Any]]

Returns as pure python object (ppo)

class tomlkit.items.Array(value: list[tomlkit.items.Item], trivia: tomlkit.items.Trivia, multiline: bool = False)

Bases: tomlkit.items.Item, tomlkit._types._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) tomlkit.items.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[typing.Any]

Returns as pure python object (ppo)

class tomlkit.items.Bool(t: int, trivia: tomlkit.items.Trivia)

Bases: tomlkit.items.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.Enum

class tomlkit.items.Comment(trivia: tomlkit.items.Trivia)

Bases: tomlkit.items.Item

A comment literal.

as_string() str

The TOML representation

class tomlkit.items.Date(year: int, month: int, day: int, *_: Any)

Bases: tomlkit.items.Item, datetime.date

A date literal.

as_string() str

The TOML representation

replace(*args: Any, **kwargs: Any) datetime.date

Return date with new specified fields.

unwrap() datetime.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: datetime.tzinfo | None, *_: Any, **kwargs: Any)

Bases: tomlkit.items.Item, datetime.datetime

A datetime literal.

as_string() str

The TOML representation

astimezone(tz: datetime.tzinfo) datetime.datetime

tz -> convert to local time in new timezone tz

replace(*args: Any, **kwargs: Any) datetime.datetime

Return datetime with new specified fields.

unwrap() datetime.datetime

Returns as pure python object (ppo)

class tomlkit.items.DottedKey(keys: Iterable[tomlkit.items.SingleKey], sep: str | None = None, original: str | None = None)

Bases: tomlkit.items.Key

class tomlkit.items.Float(value: float, trivia: tomlkit.items.Trivia, raw: str)

Bases: tomlkit.items.Item, tomlkit._types._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: tomlkit.items.AbstractTable

An inline table literal.

append(key: tomlkit.items.Key | str | None, _item: Any) tomlkit.items.InlineTable

Appends a (key, item) to the table.

as_string() str

The TOML representation

class tomlkit.items.Integer(value: int, trivia: tomlkit.items.Trivia, raw: str)

Bases: tomlkit.items.Item, tomlkit._types._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: tomlkit.items.Trivia)

Bases: object

An item within a TOML document.

as_string() str

The TOML representation

comment(comment: str) tomlkit.items.Item

Attach a comment to this item

indent(indent: int) tomlkit.items.Item

Indent this item with given number of spaces

property trivia: tomlkit.items.Trivia

The trivia element associated with this item

unwrap() Any

Returns as pure python object (ppo)

class tomlkit.items.Key

Bases: abc.ABC

Base class for a key

as_string() str

The TOML representation

concat(other: tomlkit.items.Key) tomlkit.items.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(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: enum.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: tomlkit.items.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: tomlkit.items.KeyType | None = None, sep: str | None = None, original: str | None = None)

Bases: tomlkit.items.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, tomlkit.items.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.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: tomlkit.items.AbstractTable

A table literal.

append(key: tomlkit.items.Key | str | None, _item: Any) tomlkit.items.Table

Appends a (key, item) to the table.

as_string() str

The TOML representation

indent(indent: int) tomlkit.items.Table

Indent the table with given number of spaces.

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: tomlkit.items.Key | str | None, _item: Any) tomlkit.items.Table

Similar to append() but does not copy indentation.

class tomlkit.items.Time(hour: int, minute: int, second: int, microsecond: int, tzinfo: datetime.tzinfo | None, *_: Any)

Bases: tomlkit.items.Item, datetime.time

A time literal.

as_string() str

The TOML representation

replace(*args: Any, **kwargs: Any) datetime.time

Return time with new specified fields.

unwrap() datetime.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: tomlkit.items.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: tomlkit.items.Trivia

The trivia element associated with this item

property value: str

The wrapped string of the whitespace