SoFunction
Updated on 2024-11-15

Toml configuration file in Python operation details

TOMLis a lightweight, easy-to-read data serialization format for configuration files.

Created by Tom Preston-Werner, it is intended to be a simple and intuitive profile language for any programming language environment.

TOMLSupports a wide range of data types, including strings, integers, floats, booleans, datetime, arrays, nested tables, and more.

TOMLTypically used to configure application or software settings, such as configuring database connection information, network parameters, logging levels, and so on.

In many programming languages, there are third-party libraries or native support for parsing and generatingTOMLformat configuration file.

Pythonthrough (a gap)3.11Native support starting from versionTOMLparsing, there is no need to install third-party libraries.

1. Basic types

The value of the configuration item in theTOMLIt's also like being in theJSONIn the same way, it is possible to have types.

The main basic types it says it supports arebooleannumerical value(integers, floating point numbers).string (computer science)cap (a poem)datesand several others.

1.1. Boolean values

pythonhit the nail on the headTOMLModules can be loadedtomlformalizedstring (computer science)ortomldocumentationfile stream

# -*- coding: utf-8 -*-
import tomllib
# Load toml file
with open("./", "rb") as f:
    data = (f)
print("bool_var1 = ", data["bool_var1"])
print("bool_var2 = ", data["bool_var2"])
# Running results
bool_var1 =  False
bool_var2 =  True

tomlExample of a document:

bool_var1 = false
bool_var2 = true

1.2 Numerical values

Numeric types are categorized asinteger (math.)cap (a poem)floating pointTwo kinds.

integersIn addition to decimal, hexadecimal, octal and binary can also be used.

# decimal
int_var1 = 99
int_var2 = -17
int_var3 = 1_234_000
# Hexadecimal, case sensitive
hex_var1 = 0xDE
hex_var2 = 0xde
# Binary 8
oct_var = 0o666
# Binary
bin_var = 0b11010110

After parsing, it is automatically converted to decimal.

with open("./", "rb") as f:
    data = (f)
print("int_var1 = ", data["int_var1"])
print("int_var2 = ", data["int_var2"])
print("int_var3 = ", data["int_var3"])
print("hex_var1 = ", data["hex_var1"])
print("hex_var2 = ", data["hex_var2"])
print("oct_var = ", data["oct_var"])
print("bin_var = ", data["bin_var"])
# Running results
int_var1 =  99
int_var2 =  -17
int_var3 =  1234000
hex_var1 =  222
hex_var2 =  222
oct_var =  438
bin_var =  214

floating point typeExamples of various configurations of the

float_var1 = 3.1415
float_var2 = -0.01
float_var3 = 5e+22
float_var4 = -2E-2
float_var5 = 6.626e-34

Example of parsing: various formats offloatThe writeups can all be parsed.

with open("./", "rb") as f:
    data = (f)
print("float_var1 = ", data["float_var1"])
print("float_var2 = ", data["float_var2"])
print("float_var3 = ", data["float_var3"])
print("float_var4 = ", data["float_var4"])
print("float_var5 = ", data["float_var5"])
# Running results
float_var1 =  3.1415
float_var2 =  -0.01
float_var3 =  5e+22
float_var4 =  -0.02
float_var5 =  6.626e-34

1.3. strings

For string-type configuration items, thecome individuallycap (a poem)multi-lineString.

Example configuration file:

str_single = "abcdefg"
str_multi = """ab
cd
ef
"""

Parsing Example:

with open("./", "rb") as f:
    data = (f)
print("str_single = ", data["str_single"])
print("str_multi = ", data["str_multi"])
# Running results
str_single =  abcdefg
str_multi =  ab
cd
ef

The configuration of the strings is in addition to thecome individuallyrespond in singingmulti-lineBeyond that, there aresingle quotecap (a poem)double quoteThe difference.

  • single quoteString: display string content as is
  • double quoteStrings: parsing escapes in strings
str_var1 = "ab\tcd\nef"
str_var2 = 'ab\tcd\nef'

After parsing:

with open("./", "rb") as f:
    data = (f)
print("str_var1 = ", data["str_var1"])
print("str_var2 = ", data["str_var2"])
# Running results
str_var1 =  ab  cd
ef
str_var2 =  ab\tcd\nef

1.4 Date

The last commonly used basic type isdatesType.

Configuration example:

date_var1 = 2023-09-13T10:08:22
date_var2 = 2023-09-13
date_var3 = 10:08:22

Parsing Example:

with open("./", "rb") as f:
    data = (f)
s = "date_var1 = {} (type: {})".format(data["date_var1"], 
                                       type(data["date_var1"]))
print(s)
s = "date_var2 = {} (type: {})".format(data["date_var2"], 
                                       type(data["date_var2"]))
print(s)
s = "date_var3 = {} (type: {})".format(data["date_var3"], 
                                       type(data["date_var3"]))
print(s)
# Running results
date_var1 = 2023-09-13 10:08:22 (type: <class ''>)
date_var2 = 2023-09-13 (type: <class ''>)
date_var3 = 10:08:22 (type: <class ''>)

The date type can be the fullday of the month, year, hour, minute and secondIt is also possible to have onlydays of the monthmaybehours, minutes and seconds

2. Composite types

Composite types are mainlylistingscap (a poem)dictionaries

2.1.

The elements in the list can be any of the ones described above.basic type

Configuration example: (the data types of the elements in the list can be different or it can be a list)

lst_var1 = [1, 3.14, "str", 2023-09-13T10:08:22]
lst_var2 = [[1, 2], ["abc", "def"]]

Parsing Example:

with open("./", "rb") as f:
    data = (f)
print("lst_var1 = ", data["lst_var1"])
print("lst_var2 = ", data["lst_var2"])
# Running results
lst_var1 =  [1, 
             3.14, 
             'str', 
             (2023, 9, 13, 10, 8, 22)]
lst_var2 =  [[1, 2], ['abc', 'def']]

2.2 Dictionaries

Configuration example: (the data types of the values in the dictionary can be different or it can be a dictionary)

[dict_var1]
key1 = 1
key2 = 3.14
key3 = "str"
key4 = 2023-09-13T10:08:22
[dict_var1.sub_dict]
key = "val"

Parsing Example:

with open("./", "rb") as f:
    data = (f)
print("dict_var1 = ", data["dict_var1"])
# Running results
dict_var1 =  {
    'key1': 1, 
    'key2': 3.14,
    'key3': 'str',
    'key4': (2023, 9, 13, 10, 8, 22),
    'sub_dict': {'key': 'val'}
}

3. Type combinations

If you're writing code, it's very simple to embed a dictionary in a list or a list in a dictionary.

However, it is not so easy to define such complex structures in configuration files.

TOMLSimple syntax is provided to realize combinations between complex types.

3.1. Dictionaries in lists

Configuration example:

[[student]]
name = "aaa"
age = 15
score = 100
[[student]]
name = "bbb"
age = 14
score = 89
[[student]]
name = "ccc"
age = 17
score = 98

Parsing Example:

with open("./", "rb") as f:
    data = (f)
print("students = ", data["student"])
# Running results
students =  [
    {'name': 'aaa', 'age': 15, 'score': 100},
    {'name': 'bbb', 'age': 14, 'score': 89},
    {'name': 'ccc', 'age': 17, 'score': 98},
]

3.2 Lists in dictionaries

Embedding lists in dictionaries is easier:

[teacher]
name = "abc"
classes = ["Class 1.", "Second shift.", "Three shifts."]

Parsing Example:

with open("./", "rb") as f:
    data = (f)
print("teacher = ", data["teacher"])
# Running results
teacher =  {
    'name': 'abc', 
    'classes': ['Class 1', 'Class 2', 'Class 3']
}

4. Strengths of TOML

In contrast to the commonly usedINIJSONcap (a poem)YAMLCompared to configuration files in formats such asTOMLwas born later, so it draws on their strengths and uses a simpler and more intuitive syntax and indentation format, making the document very readable and easy to edit.

(not only ...) but alsoTOMLThe format of the configuration items is closer to a scripting language and is written as if the variables were defined in code.

As opposed to the traditionalINIconfiguration compared to theTOMLexistData Type Supportas well asGrammatical flexibilityThe aspect is far superior;

together withJSONconfiguration compared to theTOMLexistsimplicityThe aspect is far superior;

together withYAMLconfiguration compared to theTOMLexistsimplicityas well asGrammatical flexibilityThe aspect is far superior.

It is because of all its advantages that the now populargolangcap (a poem)rustMany of the projects in the language start with theTOMLas a configuration file.

This article on the operation of the Toml configuration file in Python detailed article is introduced to this, more related Python Toml configuration file content, please search for my previous posts or continue to browse the following related articles I hope you will support me in the future more!