python-poetry / tomlkit

Style-preserving TOML library for Python
MIT License
701 stars 99 forks source link

Comments in multiline array #340

Closed andreasdoll closed 4 months ago

andreasdoll commented 7 months ago

Hello

I have two questions regarding comments in multiline arrays (for which I couldn't find documentation).

I'm using tomlkit 0.12.4. Consider the following code:

import tomlkit

content = """[foo]
bar = [
    "one", # comment one
    "two", # comment two
]
"""

data = tomlkit.loads(content)

I was expecting data["foo"]["bar"][0].trivia, but this doesn't have information about the comment (neither does data["foo"]["bar"].trivia). I know I can do data["foo"]["bar"].as_string() but there I'd have to parse them myself from the string.

Thanks in advance!

frostming commented 4 months ago

Comments are not tied to the array items because there is no clear relation between them, you may think there is, look at this example:

a = [
    "item1", "item2",  # type a items
    "item3", "item4",  # type b items
]

What do the comment belong to? A natural idea is that the annotation follows the previous item, right? But what should happen when user removes "item2" from the list? If the comment is with the item, it will be gone too. But in this case, the comment is about the line, not any specific item. I think you would agree the comment should remain in this case. There are other examples, too, such as comments can appear in its own line.


There are some private methods to do this:

item = array._value[array._index_map[i]]
comment = item.comment
andreasdoll commented 4 months ago

Thank you for your counter-example, I agree with your reasoning but didn't consider such a case since I'm used to write one element per line.