Skip to the solution
EasyBackend11 min read

How do you read TOML with tomllib in Python 3.11+?

715 views

The problem

Question presented to candidate: "Your service keeps its settings in a TOML file, and you are on Python 3.11. How do you read it with the standard library, what do you get back, and what can trip you up?"

What a strong answer should cover:

  • tomllib joined the standard library in Python 3.11 (PEP 680); tomllib.load(f) reads a file opened in binary mode ("rb"), tomllib.loads(s) parses a str
  • The result is a plain dict: tables become nested dicts, arrays become lists, arrays of tables ([[x]]) become lists of dicts, and dates and times become datetime objects
  • Invalid documents raise tomllib.TOMLDecodeError, a ValueError subclass, with line and column; duplicate keys are errors, unlike JSON
  • tomllib is read-only: there is no dump; use the third-party tomli-w to write or tomlkit to edit while keeping comments
  • Practical patterns: parse_float=Decimal, defaults merged with | or .get, and tomli as a fallback on Python 3.10 and older
  • Typical use: reading pyproject.toml or an app config at start-up; TOML has no null, so a missing key means "not set"

Code / implementation expected: Yes β€” with open(path, "rb") as f: config = tomllib.load(f) and reading a nested value.

  • tomllib
  • config
  • python3.11

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

11 min read Β· 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

Pythontomllib.loads: every TOML type, nested tables, arrays of tables, and TOMLDecodeError
Pythontomllib.load with rb, the text-mode error, parse_float=Decimal, defaults, and no writer

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 15 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextEasy

What is uv and why is it replacing pip/poetry in 2025-26?

Continue