tomllib — Parse TOML files

Added in version 3.11.

Source code:Lib/tomllib


This module provides an interface for parsing TOML 1.0.0 (Tom’s Obvious MinimalLanguage,https://toml.io). This module does notsupport writing TOML.

See also

TheTomli-W packageis a TOML writer that can be used in conjunction with this module,providing a write API familiar to users of the standard librarymarshal andpickle modules.

See also

TheTOML Kit packageis a style-preserving TOML library with both read and write capability.It is a recommended replacement for this module for editing alreadyexisting TOML files.

This module defines the following functions:

tomllib.load(fp,/,*,parse_float=float)

Read a TOML file. The first argument should be a readable and binary file object.Return adict. Convert TOML types to Python using thisconversion table.

parse_float will be called with the string of every TOMLfloat to be decoded. By default, this is equivalent tofloat(num_str).This can be used to use another datatype or parser for TOML floats(e.g.decimal.Decimal). The callable must not return adict or alist, else aValueError is raised.

ATOMLDecodeError will be raised on an invalid TOML document.

tomllib.loads(s,/,*,parse_float=float)

Load TOML from astr object. Return adict. Convert TOMLtypes to Python using thisconversion table. Theparse_float argument has the same meaning as inload().

ATOMLDecodeError will be raised on an invalid TOML document.

The following exceptions are available:

exceptiontomllib.TOMLDecodeError

Subclass ofValueError.

Examples

Parsing a TOML file:

importtomllibwithopen("pyproject.toml","rb")asf:data=tomllib.load(f)

Parsing a TOML string:

importtomllibtoml_str="""python-version = "3.11.0"python-implementation = "CPython""""data=tomllib.loads(toml_str)

Conversion Table

TOML

Python

TOML document

dict

string

str

integer

int

float

float (configurable withparse_float)

boolean

bool

offset date-time

datetime.datetime (tzinfo attribute set to an instance ofdatetime.timezone)

local date-time

datetime.datetime (tzinfo attribute set toNone)

local date

datetime.date

local time

datetime.time

array

list

table

dict

inline table

dict

array of tables

list of dicts