Skip to main content

Import tomllib in Python

Python versions 3.11+ ship with a version of Tomli: the tomllib standard library module.

In requirements.txt:

tomli >= 1.1.0 ; python_version < "3.11"

With Poetry, in pyproject.toml:

[tool.poetry.dependencies]
tomli = { version = "^2.0.1", python = "<3.11" }

In Python code (Python 3 >= 3.6):

import sys
if sys.version_info >= (3, 11):
    import tomllib
else:
    try:
        import tomli as tomllib
    except ModuleNotFoundError as e:
        raise ModuleNotFoundError("Is tomli module installed?") from e

Ref: Tomli on tomllib compatibility

Ref: Python “raise from” usage