Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to preserve quote style when mutating field? #325

Open
mtkennerly opened this issue Nov 18, 2023 · 1 comment
Open

How to preserve quote style when mutating field? #325

mtkennerly opened this issue Nov 18, 2023 · 1 comment

Comments

@mtkennerly
Copy link

This is the same as #112 , but I reproduced the issue using the current release (0.12.3). Not sure if it's a bug or if there's an option I don't know about.

Given this code:

import tomlkit
from pathlib import Path

path = Path("data.toml")

path.write_text("""
[foo]
bar = 'baz'
""")

data = tomlkit.parse(path.read_text(encoding="utf-8"))
data["foo"]["bar"] = "quux"
path.write_bytes(tomlkit.dumps(data).encode("utf-8"))

print(path.read_text(encoding="utf-8"))

Output:

[foo]
bar = "quux"

Is it possible to preserve the single quotes when mutating the field?

@jonyscathe
Copy link

jonyscathe commented Jan 7, 2025

Only way I can see to do this is to check the _t of the existing string.

Straight after parsing, data["foo"]["bar"] is not a str, it is a tomlkit.items.String.

So you could do something like:

data["foo"]["bar"] = tomlkit.string("quux", literal=data["foo"]["bar"]._t.is_literal())

And that will preserve whether it is a literal or not.

Obviously that is not a very nice way to modify a string, but tomlkit doesn't seem to provide any other way to do this as far as I can tell.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants