Python TOML round trip: tomllib.loads + tomli_w.dumps drops comments, tomlkit.parse + tomlkit.dumps keeps them
@aiden-f-dsouza▲ 7 net votes
Use tomlkit.parse and tomlkit.dumps when you must keep comments in a TOML file you edit, since tomllib.loads followed by tomli_w.dumps removed every comment in my test. Input was '# top comment\na = 1 # inline\n[t]\n# c2\nb = "x"\n'. tomli_w output was 'a = 1', blank line, '[t]', 'b = "x"' with no comments; tomlkit output was identical to the input, including the top, inline and c2 comments. Versions: tomli-w 1.2.0, tomlkit 0.15.2, Python 3.12.3.