Tomli is a Python library for parsing TOML

Overview

Build Status codecov.io PyPI version

Tomli

A lil' TOML parser

Table of Contents generated with mdformat-toc

Intro

Tomli is a Python library for parsing TOML. Tomli is fully compatible with TOML v1.0.0.

Installation

pip install tomli

Usage

Parse a TOML string

import tomli

toml_str = """
           gretzky = 99

           [kurri]
           jari = 17
           """

toml_dict = tomli.loads(toml_str)
assert toml_dict == {"gretzky": 99, "kurri": {"jari": 17}}

Parse a TOML file

import tomli

with open("path_to_file/conf.toml", encoding="utf-8") as f:
    toml_dict = tomli.load(f)

Handle invalid TOML

import tomli

try:
    toml_dict = tomli.loads("]] this is invalid TOML [[")
except tomli.TOMLDecodeError:
    print("Yep, definitely not valid.")

Note that while the TOMLDecodeError type is public API, error messages of raised instances of it are not. Error messages should not be assumed to stay constant across Tomli versions.

Construct decimal.Decimals from TOML floats

from decimal import Decimal
import tomli

toml_dict = tomli.loads("precision-matters = 0.982492", parse_float=Decimal)
assert isinstance(toml_dict["precision-matters"], Decimal)

Note that you may replace decimal.Decimal with any callable that converts a TOML float from string to any Python type (except list or dict). The decimal.Decimal type is, however, the most typical replacement when float inaccuracies can not be tolerated.

FAQ

Why this parser?

  • it's lil'
  • pure Python with zero dependencies
  • the fastest pure Python parser *: 14x as fast as tomlkit, 2.4x as fast as toml
  • outputs basic data types only
  • 100% spec compliant: passes all tests in a test set soon to be merged to the official compliance tests for TOML repository
  • thoroughly tested: 100% branch coverage

Is comment preserving round-trip parsing supported?

No.

The tomli.loads function returns a plain dict that is populated with builtin types and types from the standard library only. Preserving comments requires a custom type to be returned so will not be supported, at least not by the tomli.loads and tomli.load functions.

Look into TOML Kit if preservation of style is what you need.

Is there a dumps, write or encode function?

Tomli-W is the write-only counterpart of Tomli, providing dump and dumps functions.

The core library does not include write capability, as most TOML use cases are read-only, and Tomli intends to be minimal.

How do TOML types map into Python types?

TOML type Python type Details
Document Root dict
Key str
String str
Integer int
Float float
Boolean bool
Offset Date-Time datetime.datetime tzinfo attribute set to an instance of datetime.timezone
Local Date-Time datetime.datetime tzinfo attribute set to None
Local Date datetime.date
Local Time datetime.time
Array list
Table dict
Inline Table dict

Performance

The benchmark/ folder in this repository contains a performance benchmark for comparing the various Python TOML parsers. The benchmark can be run with tox -e benchmark-pypi. Running the benchmark on my personal computer output the following:

[email protected]:~/dev/tomli$ tox -e benchmark-pypi
benchmark-pypi installed: attrs==19.3.0,click==7.1.2,pytomlpp==1.0.2,qtoml==0.3.0,rtoml==0.7.0,toml==0.10.2,tomli==1.0.4,tomlkit==0.7.2
benchmark-pypi run-test-pre: PYTHONHASHSEED='2995948371'
benchmark-pypi run-test: commands[0] | python -c 'import datetime; print(datetime.date.today())'
2021-07-05
benchmark-pypi run-test: commands[1] | python --version
Python 3.8.5
benchmark-pypi run-test: commands[2] | python benchmark/run.py
Parsing data.toml 5000 times:
------------------------------------------------------
    parser |  exec time | performance (more is better)
-----------+------------+-----------------------------
     rtoml |    0.902 s | baseline (100%)
  pytomlpp |     1.09 s | 83.00%
     tomli |     3.82 s | 23.60%
      toml |     9.27 s | 9.73%
     qtoml |     11.5 s | 7.84%
   tomlkit |     55.1 s | 1.64%

The parsers are ordered from fastest to slowest, using the fastest parser as baseline. Tomli performed the best out of all pure Python TOML parsers, losing only to pytomlpp (wraps C++) and rtoml (wraps Rust).

Owner
Taneli Hukkinen
Taneli Hukkinen
SQS + Lambda를 활용한 문자 메시지 및 이메일, Voice call 호출을 간단하게 구현하는 serverless 템플릿

AWS SQS With Lambda notification 서버 구축을 위한 Poc TODO serverless를 통해 sqs 관련 리소스(람다, sqs) 배포 가능한 템플릿 작성 및 배포 poc차원에서 간단한 rest api 호출을 통한 sqs fifo 큐에 메시지

김세환 4 Aug 08, 2021
gnosis safe tx builder

Ape Safe: Gnosis Safe tx builder Ape Safe allows you to iteratively build complex multi-step Gnosis Safe transactions and safely preview their side ef

228 Dec 22, 2022
Check AWS S3 instances for read/write/delete access

s3sec Test AWS S3 buckets for read/write/delete access This tool was developed to quickly test a list of s3 buckets for public read, write and delete

0xmoot 114 Dec 06, 2022
Join & Leave spam for aminoapps using aminoboi

JLspam.py Join & Leave spam for https://aminoapps.com using aminoboi Instalação apt-get update -y apt-get upgrade -y apt-get install git pkg install

Moleey 1 Dec 21, 2021
This is a Python bot, which automates logging in, purchasing and planting the seeds. Open source bot and completely free.

🌻 Sunflower Land Bot 🌻 ⚠️ Warning I am not responsible for any penalties incurred by those who use the bot, use it at your own risk. This BOT is com

Newerton 18 Aug 31, 2022
Scuttlecrab.py - Python Version of Scuttle Crab Bot

____ _ _ _ ____ _ / ___| ___ _ _| |_|

Fabrizo 4 Jul 08, 2022
Sadew Jayasekara 23 Oct 21, 2022
Python SDK for Thepeer

Python SDK for Thepeer

Oluwafemi Tairu 2 Dec 22, 2021
Python SDK for Facebook's Graph API

Facebook Python SDK This client library is designed to support the Facebook Graph API and the official Facebook JavaScript SDK, which is the canonical

Mobolic 2.7k Jan 07, 2023
A telegram bot which can show you the status of telegram bot

BotStatus-Ts-Bot An open source telegram Bot Status bot For demo you can check here The status is updated in every 1 hour About Bot This is a Bot stat

Ts_Bots 8 Nov 17, 2022
ZenML 🙏: MLOps framework to create reproducible ML pipelines for production machine learning.

ZenML is an extensible, open-source MLOps framework to create production-ready machine learning pipelines. It has a simple, flexible syntax, is cloud and tool agnostic, and has interfaces/abstraction

ZenML 2.6k Dec 27, 2022
Embed the Duktape JS interpreter in Python

Introduction Pyduktape is a python wrapper around Duktape, an embeddable Javascript interpreter. On top of the interpreter wrapper, pyduktape offers e

Stefano 78 Dec 15, 2022
Python Business Transactions Library - ContractsPY

Python Business Transactions Library - ContractsPY Declare and define business transactions in Python. Use the contracts library to validate business

Arzu Huseynov 7 Jun 21, 2022
Sunflower-farmers-automated-bot - Sunflower Farmers NFT Game automated bot.IT IS NOT a cheat or hack bot

Sunflower-farmers-auto-bot Sunflower Farmers NFT Game automated bot.IT IS NOT a

Arthur Alves 17 Nov 09, 2022
WallAlley.bot is an open source and free to use financial discord bot originaly build for WallAlley server's community

WallAlley.bot About WallAlley.bot is an open source and free to use financial discord bot originaly build for WallAlley server's community. All data a

Mohammad KHADDAN 1 Jan 22, 2022
The fastest nuker on discord, Proxy support and more

About okuru nuker is a nuker for discord written in python, It uses methods such as threading and requests to ban faster and perform at higher speeds.

63 Dec 31, 2022
Бот для скачивания треков с Deezer используя ISRC и UPC коды

deez_robot Запуск Установите необходимые библиотеки pip install -r requirements.txt Создайте файл config.py и поместите туда токен бота и ARL-токен De

Max 4 Jul 31, 2022
Python package for Calendly API v2

PyCalendly Python package to use Calendly API-v2. Installation Install with pip $ pip install PyCalendly Usage Getting Started See Getting Started wi

Lakshmanan Meiyappan 20 Dec 05, 2022
BLYRIC is a Twitter bot that tweets a song lyric every night.

BLYRIC BLYRIC, a bot that tweets a song lyric every night. Follow on Twitter: @blyric_ Overview BLYRIC is a Twitter bot that tweets a song quote every

Bruno Kenzo Hyodo 6 Oct 05, 2022
TESSARECT A Powerful Bot you'll ever need for anything

Tessarect TESSARECT A Powerful Bot you'll ever need for anything TESSARECT It is my First bot but very advanced and designed for all your needs , from

Prakarsh Prp 4 Aug 27, 2022