00:00 In the previous lesson, I showed you how traceback information now has detailed indicators that can help you find the cause of your errors. In this lesson, I’ll be showing you TOML, the configuration language that is now part of the standard library.
00:15 TOML is short for Tom’s Obvious, Minimal Language and is a configuration file format. If you’ve ever seen Windows INI files, it’s quite similar to those. TOML’s been around for a long time, but up until 3.11 could only be used in Python with a third-party package.
With this prevalence, it kind of makes sense to add TOML to the list of included batteries. This is a simple TOML file. Straightforward, huh? With the exception of the fact that
true isn’t capitalized, this could be Python. For a lot of configuration data, this might be all you needed. TOML also supports grouping of keys, though.
This is a more complicated TOML file. You can define a section using square brackets (
). You can think of this as a grouping of configuration items or, from a Python perspective, nested dictionaries. Note that it also supports lists.
Each section in the TOML file becomes a nested dictionary in the result. Since the data types in TOML are very similar to those in Python, there isn’t much in the way of surprises here. It is even
datetime aware, converting the date string in the TOML file into
datetime object in Python.
TOML becoming part of Python’s standard library is a good thing. It’s being used more and more in the ecosystem. black, mypy, pytest, and many more already use TOML for their configuration. To be consistent with Python 3, only UTF-8-based files are supported, and the interface has been written to be similar to how JSON and
04:36 Why am I bringing that random fact up? Well, if you’re using a third-party TOML library, they don’t use that style of interface. The two more popular libraries allow you to load using just the filename.
Python has decided consistency is better, so you’re stuck using the file handle or
.readtext() mechanism that I showed you. As TOML is primarily used as a configuration format, it has also been decided to not support the writing of files.
05:03 If you want to programmatically generate TOML files, you’re encouraged to use third-party libraries. TOML Kit is one of the more popular one of those. It has the benefit of also being style preserving, which means when you read the file in and then write it out, it will look the same. That sounds like a simple thing, but parsers for a lot of text formats don’t do this.
Become a Member to join the conversation.