The Python service and the Go binary read the same service.toml, and they disagree about it. An
upstream with wieght = 3 gets weight 1 from a loader that reads keys with defaults, in both
languages, with no error. The maintenance window, 2026-12-01T02:00:00, is a naive datetime in
Python and an instant at the host’s offset in Go, so Go’s window moves with the machine.
What you get
You will end up with a Python service and a Go binary that load one TOML file into typed structures and print the same JSON dump from it, as a test checks. This is for you if two languages share a config file.
Short answer
Load the file with tomllib into dataclasses in Python, and with BurntSushi/toml or
pelletier/go-toml v2 into structs in Go. tomllib reports no unknown keys, so compare the keys
against the dataclass fields yourself. In Go, check MetaData.Undecoded or call
DisallowUnknownFields. Give instants an offset, dump them in UTC, and print local date-times as
wall-clock text, so both dumps match.
You will need
Python 3.11 or later, where tomllib is in the standard library, and Go 1.24 or later. Verified
2026-11-30 against Python 3.12.3 and 3.13.18, Go 1.24.7 and 1.25.14, BurntSushi/toml 1.6.0,
pelletier/go-toml 2.4.3, tomli 2.5.0 and tomli-w 1.2.0. The date and time types come from the
TOML 1.0.0 specification, which is the edition the
tomllib documentation names.
Approaches compared
| Approach | When it fits | What it costs you | When to pick something else |
|---|---|---|---|
| BurntSushi/toml | A Go binary that wants the keys it ignored as a list, in file order | Unknown keys are your check to write, and a time.Time field turns a local date-time into an instant | You want decoding to fail by itself on a stray key, with no list to check |
| pelletier/go-toml v2 | A Go binary that should refuse a stray key while decoding | Strict mode is opt-in per decoder, and a local date-time in a time.Time takes time.Local | You want to log stray keys and still start, which needs the list Undecoded returns |
tomli | Python 3.10 or earlier, or TOML 1.1 syntax before Python 3.15 | A dependency, binary wheels per platform, and no writer, which needs tomli-w | The runtime is Python 3.11 or later and files stay on TOML 1.0 |
tomllib | Python 3.11 or later, files written to TOML 1.0 | No unknown-key detection, no writer, and TOML 1.1 syntax refused | The Go side accepts TOML 1.1 syntax that clients will write |
tomllib and tomli return plain dictionaries and report nothing they did not expect, so the key
check lives in your loader. Both Go libraries can refuse a stray key. BurntSushi lists the keys you
did not decode, while go-toml v2 fails the decode itself. tomli costs a dependency and, in return,
reads TOML 1.1, which both Go libraries also read.
Load it in Python with tomllib
tomllib.load returns a dictionary. The loader compares its keys with the dataclass fields, checks
the scalar types, refuses a required key that is missing or empty, and refuses an instant without
an offset.
def _check_keys(table, cls, where):
# tomllib returns every key it read and reports none it did not expect.
types = {f.name: f.type for f in fields(cls)}
unknown = sorted(set(table) - set(types))
if unknown:
raise ConfigError(f"unknown key {where}{unknown[0]}")
for key, value in table.items():
want = types[key]
if want in (int, str, datetime) and type(value) is not want:
raise ConfigError(f"{where}{key} is {type(value).__name__}, want {want.__name__}")
for f in fields(cls):
required = f.default is MISSING and f.default_factory is MISSING
if required and table.get(f.name, "") == "":
raise ConfigError(f"{where}{f.name} is required")
def load(path):
with open(path, "rb") as f:
raw = tomllib.load(f)
_check_keys(raw, Config, "")
entries = raw.pop("upstream", [])
if not isinstance(entries, list) or not all(isinstance(e, dict) for e in entries):
raise ConfigError("upstream must be an array of tables")
ups = []
for i, entry in enumerate(entries):
_check_keys(entry, Upstream, f"upstream[{i}].")
ups.append(Upstream(**entry))
cfg = Config(**raw, upstream=ups)
# An offset date-time loads as an aware datetime, a local one as naive.
if cfg.deployed_at.tzinfo is None:
raise ConfigError("deployed_at has no UTC offset")
if cfg.maintenance.tzinfo is not None:
raise ConfigError("maintenance must be a local date-time")
return cfg
The dump puts instants in UTC with a Z and prints a local date-time with no offset, so neither
language’s default formatting reaches the comparison.
python3 py/dump.py service.toml
{
"deployed_at": "2026-11-29T08:30:00Z",
"maintenance": "2026-12-01T02:00:00",
"name": "checkout",
"port": 8080,
"timeout_secs": 45,
"upstream": [
{
"name": "payments",
"url": "http://127.0.0.1:9001",
"weight": 3
},
{
"name": "ledger",
"url": "http://127.0.0.1:9002",
"weight": 1
}
]
}
port came from the default and the second upstream’s weight from the dataclass, while
timeout_secs came from the file.
Load it in Go with either library
A decoder fills only the fields the file sets, so set the defaults on the struct before decoding.
For a weight inside an array of tables, a *int tells a missing key from an explicit zero.
BurntSushi needs one more step. A time.Time field receives its value through UnmarshalText,
which drops the marker that says the value had no offset.
// bsLocal and bsInstant see the value BurntSushi parsed before it reaches
// a time.Time field. A plain time.Time field goes through UnmarshalText,
// which turns a local date-time into an instant at the machine's offset.
type bsLocal struct{ time.Time }
type bsInstant struct{ time.Time }
// BurntSushi gives a local date-time a fixed zone named "datetime-local"
// (internal/tz.go), and local dates and times "date-local" and "time-local".
func bsZoneIsLocal(t time.Time) bool { return strings.HasSuffix(t.Location().String(), "-local") }
func (l *bsLocal) UnmarshalTOML(v any) error {
t, ok := v.(time.Time)
if !ok || t.Location().String() != "datetime-local" {
return errors.New("maintenance must be a local date-time")
}
l.Time = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), time.UTC)
return nil
}
func (i *bsInstant) UnmarshalTOML(v any) error {
t, ok := v.(time.Time)
if !ok || bsZoneIsLocal(t) {
return errors.New("deployed_at has no UTC offset")
}
i.Time = t
return nil
}
UnmarshalTOML sees the parsed
value first, and BurntSushi names the zone of a local date-time datetime-local. go-toml v2 needs
no wrapper, because it decodes a local date-time into its own
LocalDateTime type, which
has no zone. It does decode a lone [upstream] table into a slice of one, which BurntSushi and
tomllib refuse, so its loader checks the raw value before decoding.
Check it worked
config_test.go runs py/dump.py, loads the same file with both Go libraries, and compares the
three dumps byte for byte. It repeats the comparison with the zone set to Tokyo and refuses twelve
broken files in all three loaders.
go test -count=1 -v ./... | grep -E '^(=== RUN|--- FAIL|FAIL)'
=== RUN TestPythonAndBothGoLoadersPrintTheSameJSON
=== RUN TestTheDumpDoesNotDependOnTheMachineZone
=== RUN TestAPlainTimeFieldTakesTheMachineZone
=== RUN TestAllThreeRefuseTheSameFiles
=== RUN TestAnExplicitZeroWeightIsKept
=== RUN TestTimesWithoutSecondsSplitTheLanguages
No FAIL line appears. The Python side has its own tests, which need npm ci first for tomli and
tomli-w.
python3 -m unittest discover -s py -v 2>&1 | grep -E ' \.\.\. |^OK|^FAILED'
test_a_misspelled_key_is_refused (test_config.LoadTest.test_a_misspelled_key_is_refused) ... ok
test_an_instant_without_offset_is_refused (test_config.LoadTest.test_an_instant_without_offset_is_refused) ... ok
test_defaults_fill_keys_left_out (test_config.LoadTest.test_defaults_fill_keys_left_out) ... ok
test_instants_are_dumped_in_utc (test_config.LoadTest.test_instants_are_dumped_in_utc) ... ok
test_tomli_parses_like_tomllib (test_config.LoadTest.test_tomli_parses_like_tomllib) ... ok
test_tomli_reads_toml_1_1_times_that_tomllib_refuses (test_config.LoadTest.test_tomli_reads_toml_1_1_times_that_tomllib_refuses) ... ok
test_tomllib_has_no_writer_and_tomli_w_round_trips (test_config.LoadTest.test_tomllib_has_no_writer_and_tomli_w_round_trips) ... ok
OK
When it goes wrong
The maintenance window moves with the host. Decode the two date-times into plain fields, and Python
gives one aware and one naive datetime.
python3 py/naive.py service.toml
python deployed_at 2026-11-29T09:30:00+01:00 tzinfo=UTC+01:00
python maintenance 2026-12-01T02:00:00 tzinfo=None
Go gives two instants, and the one without an offset takes the zone of whatever machine runs it.
TZ=Asia/Tokyo go run ./cmd/naive service.toml
burnt deployed_at "2026-11-29T09:30:00+01:00"
burnt maintenance "2026-12-01T02:00:00+09:00"
go-toml deployed_at "2026-11-29T09:30:00+01:00"
go-toml maintenance "2026-12-01T02:00:00+09:00"
The specification leaves that conversion to the implementation, so neither result is a bug.1
Write an offset on anything that names a moment, and keep a local date-time for wall-clock values,
as service.toml does.
A misspelled key takes the default. Neither language complains until you ask it to.
python3 py/typo.py typo.toml
entry.get('weight', 1): 1, tomllib returned ['name', 'url', 'wieght']
with key check: unknown key upstream[0].wieght
go run ./cmd/typo typo.toml
burnt, Decode alone: weight=1
go-toml, Unmarshal alone: weight=1
burnt, Undecoded(): unknown key upstream.wieght
go-toml, strict decoder: unknown key upstream.wieght
A file that loads in Go fails in Python. TOML 1.1 lets a time leave out its seconds, and both Go
libraries and tomli accept 2026-12-01T02:00, while tomllib on Python 3.12 follows TOML 1.0.
python3 py/dump.py no-seconds.toml; go run ./cmd/dump no-seconds.toml | head -3
refused: Expected newline or end of document after a statement (at line 2, column 25)
{
"deployed_at": "2026-11-29T08:30:00Z",
"maintenance": "2026-12-01T02:00:00",
Keep shared files on TOML 1.0 syntax, or load them with tomli 2.4 or later until the runtime has a
tomllib that reads 1.1.2
Write the file back
tomllib has no writer, so a tool that edits the config needs tomli-w, and tomli is a drop-in
parser with the same results on this file.
PYTHONPATH=pydeps python3 py/alt.py service.toml
tomllib writes TOML: False
tomli 2.5.0 equals tomllib: True
tomli-w 1.2.0 round trip: True
tomli-w output, first lines:
name = "checkout"
timeout_secs = 45
deployed_at = 2026-11-29 09:30:00+01:00
maintenance = 2026-12-01 02:00:00
upstream = [
{ name = "payments", url = "http://127.0.0.1:9001", weight = 3 },
The round trip keeps every value. It drops the comments and rewrites the [[upstream]] tables as
an inline array, so tomli-w suits a file a tool owns, not one people also edit by hand.
When not to do this
Do not add a third language to the file without a loader test like config_test.go for it.
Each parser makes its own choices about local date-times and TOML 1.1 syntax, and the dump
comparison is what catches them.
Do not rely on either Go library’s default decoder for a file people edit by hand. Both accepted
wieght without a word until Undecoded or DisallowUnknownFields was in the path.
Do not choose TOML for deeply nested data. Arrays of tables inside tables are hard to read, and every level adds a header line that a reader must match to its parent.
Related how-tos
Last verified
Verified 2026-11-30 against Python 3.12.3 and 3.13.18, Go 1.24.7 and 1.25.14, BurntSushi/toml
1.6.0, pelletier/go-toml 2.4.3, tomli 2.5.0 and tomli-w 1.2.0. Every output block is what the
command preceding it printed. All four approaches ran.
Footnotes
-
TOML 1.0.0 says a local date-time “cannot be converted to an instant in time without additional information.” Any conversion is left to the implementation. BurntSushi’s source records its choice in a comment in
internal/tz.go: the offset of the computer, which the comment calls valid according to the TOML specification. ↩︎ Back to text -
The TOML changelog dates 1.0.0 to 2021-01-11 and 1.1.0 to 2025-12-18, almost five years apart for an edition whose changes include optional seconds. The
tomliREADME callstomlia TOML 1.1.0 backport for Python versions below 3.15, and offerstomli<2.4to anyone on 3.15 or later who wants 1.0.0 back. ↩︎ Back to text