# Data : TOML \[ [spec](https://toml.io/en/v1.0.0) ] ```toml key = value # comment [ section ] key = value ``` ###### Basics - latest version: `1.0.0` - extension: `.toml` - media type: `application/toml` - encoding: `utf-8` - documents map to a hash table — like a JSON file containing a top-level object - keys are case-sensitive, and can be bare (A-Za-z0-9_-) or quoted - keys can be dotted (foo.bar) - whitespace is optional around keys, values, `=`, `.`, and `[` / `]` - sections are "tables" — names follow the same rules as keys - the top-level table (aka "root table") starts at the top and ends at the first section - lists and inline tables can be nested - comments (`#`) can start anywhere ###### Types - boolean — `true`, `false` - integer & float - supports E-notation (`1e+2`) - supports binary (`0b01`), octal (`0o07`), and hex (`0x0F`) - supports separators (`123_456`) - supports `inf/-inf` and `nan/-nan` - string - basic strings (`"..."`, `"""..."""`) support escape sequences - literal strings (`'...'`, `'''...'''`) do not - multiline strings (`"""..."""`, `'''...'''`) can use `\` at end of line to trim indentation on next line - array — `[ 1, 2, "foo" ]` - inline table — `{ a=1, b=2 }` - Python's `tomlib` module conforms to TOML v1.0.0, which doesn't allow newlines in inline tables. However, the [next version](https://github.com/toml-lang/toml/blob/main/CHANGELOG.md) of TOML will [allow it](https://github.com/toml-lang/toml/pull/904/files). - offset datetime — `1970-01-01T01:23:45.123456Z`, `1970-01-01T01:23:45.123456-05:00` - local datetime — `1970-01-01T01:23:45.123456` - local date — `1970-01-01` - local time — `01:23:45.123456` ## Python #### tomllib (stdlib as of v3.11) \[ [docs](https://docs.python.org/3/library/tomllib.html) ] ```python from tomllib import load, loads, TOMLDecodeError # both return dicts or raise TOMLDecodeError load( open_file ) loads( string ) with open( path, "rb" ) as f: data = tomllib.load( f ) ``` #### tomlkit \[ [pypi](https://pypi.org/project/tomlkit/) | [src](https://github.com/sdispater/tomlkit/) | [docs](https://tomlkit.readthedocs.io/en/latest/) ] Style-preserving library for reading *and* writing. ```python from tomlkit import dump, dumps, load, loads, parse (same as loads) from tomlkit import comment, document, nl, table doc = parse( string ) # returns TOMLDocument object dumps( doc ) == string -or- doc.as_string() # check key in doc # get val = doc[ key ] val = doc[ missing_key ] # raises tomlkit.exceptions.NonExistentKey val = doc.get( key[, default] ) # if key missing, returns default or None # set doc.add( comment( "..." ) ) doc.add( nl() ) # newline doc.add( key, val ) -or- doc[ key ] = val doc.update( mydict ) doc[ key ].comment( "..." ) # add comment on same line as key # delete doc.remove( key ) -or- del doc[ key ] val = doc.pop( key ) # constructing new objects doc = document() # returns TOMLDocument object tab = table() # returns Table object - similar API to documents ```