Updating Existing TOML Documents
00:00 Update Existing TOML Documents. Imagine you’ve spent some time putting together a well-organized configuration with good comments that instructs your users how they can change it.
00:11 Then, another application comes along and stores its configuration in the same file, destroying your carefully crafted work of art. This might be an argument for keeping your configuration in a dedicated file that no one else will touch, but sometimes it’s convenient to use a common configuration file as well.
00:27
The pyproject.toml
file is used as such a common file, especially for tools that you use when developing and building packages. If you want to learn more about pyproject.toml
, then Real Python has you covered with this video course.
00:44
In this part of the course, you’ll dive deeper into how tomlkit
represents TOML objects and how you can use the package to update existing TOML files.
00:53
Earlier in the course, you saw that tomli
and tomllib
parse a TOML document into native Python types such as strings, integers, and dictionaries.
01:02
You’ve seen some indications that tomlkit
is different, and now it’s time to look closer at how tomlkit
represents a TOML document.
01:11
First, make sure you’ve downloaded tic-tac-toe-config
.toml
from the course materials. You can see its content on screen.
01:25
Then open a REPL session, and load the document with tomlkit
.
01:43
Note that unlike tomli
, tomlkit
expects you to open the file in text mode. You should also remember to specify that the file should be opened using the UTF-8
encoding.
01:53
When you look at config
, it looks like a dictionary at first glance, but digging deeper, you’ll find that it’s a special TOML document type. tomlkit
’s native data types behave more or less like native Python types.
02:11 and values in the document using square brackets just like dictionaries.
02:25
Even though the values are also special tomlkit
data types, you can work with them as if they’re regular Python types. For example, you can use the upper
string method.
02:39
One advantage of the special data types is they give you access to meta information about the document, including comments and indentation. You recover comment and indentation information through the trivia
accessor.
03:06 As you’ve already seen, you can mostly treat these special objects as if they were native Python objects. In fact, they inherit from their native counterparts.
03:24
But if you really need to, you can use unwrap()
to convert them to plain Python.
03:39
After unwrap()
is called, the 3
is now a regular Python integer. This investigation gives you some insight into how tomlkit
is able to preserve the style of TOML documents.
03:52
In the next section of the course, you’ll learn how you can use tomlkit
data types to customize the TOML document, without affecting the existing style.
Become a Member to join the conversation.