Creating TOML From Scratch
00:00
Create TOML From Scratch With tomlkit
. tomlkit
was originally built for the Poetry project. As part of its dependency management, Poetry manipulates the py
project.toml
file.
00:12
Since this file is used for many purposes, Poetry must preserve the style and comments within the file. In this section of the course, you’ll create a TOML document from scratch with tomlkit
in order to play with some of its functionality. First, you need to install the package into your virtual environment.
00:38
You can start by confirming that tomlkit
is more powerful than tomli
and tomli_w
. Redo the round-trip example from earlier, and note that all of the formatting is preserved.
01:03
You can use loads()
and dumps()
, and load()
and dump()
to read and write TOML as earlier, but now all your string types, indentations, comments, and alignments are preserved.
01:21
To achieve this, tomlkit
uses custom data types that behave more or less like native Python types. You’ll learn more about these data types later.
01:31 But first, you’ll see how you can create a TOML document from scratch.
01:40
In general, you need to start by calling document()
to create a TOML document instance. You can then use add()
to add different objects to the document, such as comments, newlines, key-value pairs, and tables.
02:04
Note that calling add()
returns the updated object. Later, you’ll see how you can take advantage of this design and chain together several calls to add()
.
02:14
You can convert TOML to an actual TOML document by using dump()
or dumps()
as seen previously, or you can use the .as_string()
method.
02:25
Here you are starting to re-create parts of the tic-tac-toe
configuration that you’ve worked with previously. Note how each line in the output corresponds to an add()
method in the code.
02:36
First, you have the comment, then nl
representing a blank line, and then the key-value pair. Continue by adding a few tables. You create tables by calling table()
and adding content to them.
03:05
After you’ve created a table, you add it to the TOML document. You can stick to using add()
to assemble the document, but you can also use alternative ways such as update()
to add keys and values directly from a dictionary.
03:36 When you convert your document to a TOML string, it will look as seen on screen.
03:45
Compare this output with the commands that you use to create the document. If you’re creating a TOML document with a fixed structure, then it’s probably easier to write the document as a TOML string and then load it with tomlkit
.
03:58
But the commands you’ve just seen give you much more flexibility when dynamically putting together your configuration. With the creation of TOML documents covered, in the next section of the course, you’ll dig deeper into tomlkit
and see how you can use it to update existing configurations.
Become a Member to join the conversation.