Skip to content

0.15.3: str-based Enum values are written as "Color.RED" instead of their value #725

Backlog

Description

@yiidtw

Since 0.15.3, a value that is a str subclass with its own __str__, such as a (str, Enum) member, is written using __str__ instead of its string value. 0.15.2 wrote the value.

import enum, tomlkit

class Color(str, enum.Enum):
    RED = "red"

doc = tomlkit.document()
doc["color"] = Color.RED
print(tomlkit.dumps(doc))
tomlkit Python 3.10.19 Python 3.12.3
0.15.2 (PyPI) color = "red" color = "red"
0.15.3 (PyPI) color = "Color.RED" color = "Color.RED"

If __str__ returns text with a quote, the output is not valid TOML. For example, with def __str__(self): return 'shown "x' the output is k = "shown "x", and tomlkit.parse rejects it.

It starts at 73078ea ("Speed up escaping strings and keys when writing TOML", #709). When no character needs escaping, escape_string in tomlkit/_utils.py now returns str(s). For a str subclass that calls the subclass's __str__. Before #709 the result was built from the characters of s, so it was always the underlying string. return str.__str__(s) keeps the speed-up and returns the underlying text; with that one-line change on master (3cdcbde) the example prints color = "red" and the test suite passes (803 passed, 1 skipped, tests/test_toml_tests.py excluded because its data files are not in the checkout).

Found while testing code-review tools on recent tomlkit commits; reproduced with the PyPI wheels above.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions