From 0c45a5126c44fd022dbf20aed1acd891d83c47df Mon Sep 17 00:00:00 2001 From: Sam Vente Date: Mon, 2 Jun 2025 10:33:14 +0200 Subject: [PATCH 1/2] Fix: accept ints as keys (interpret them as strings) --- tests/test_toml_document.py | 5 +++++ tomlkit/items.py | 6 +++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/tests/test_toml_document.py b/tests/test_toml_document.py index ae18ff1..60d3fe7 100644 --- a/tests/test_toml_document.py +++ b/tests/test_toml_document.py @@ -15,6 +15,7 @@ from tomlkit._utils import _utc from tomlkit.api import document from tomlkit.exceptions import NonExistentKey +from tomlkit.toml_document import TOMLDocument def test_document_is_a_dict(example): @@ -1187,3 +1188,7 @@ def test_overwrite_out_of_order_table_key(): """ ) + + +def test_set_default_int(): + TOMLDocument().setdefault(4, 5) diff --git a/tomlkit/items.py b/tomlkit/items.py index b80e9f1..a011e45 100644 --- a/tomlkit/items.py +++ b/tomlkit/items.py @@ -375,11 +375,15 @@ class SingleKey(Key): def __init__( self, - k: str, + k: str | int, t: KeyType | None = None, sep: str | None = None, original: str | None = None, ) -> None: + # keys are allowed to be ints but should be interpreted as strings + if not isinstance(k, str): + k = str(k) + if t is None: if not k or any( c not in string.ascii_letters + string.digits + "-" + "_" for c in k From 6bbb9e9d12ff10d234be83a469776b1416d113cd Mon Sep 17 00:00:00 2001 From: Sam Vente Date: Tue, 3 Jun 2025 07:32:07 +0200 Subject: [PATCH 2/2] fix: throw type error instead of casting to str --- tests/test_toml_document.py | 3 ++- tomlkit/items.py | 5 ++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/test_toml_document.py b/tests/test_toml_document.py index 60d3fe7..f99a779 100644 --- a/tests/test_toml_document.py +++ b/tests/test_toml_document.py @@ -1191,4 +1191,5 @@ def test_overwrite_out_of_order_table_key(): def test_set_default_int(): - TOMLDocument().setdefault(4, 5) + with pytest.raises(TypeError): + TOMLDocument().setdefault(4, 5) diff --git a/tomlkit/items.py b/tomlkit/items.py index 05fd7e3..456dc83 100644 --- a/tomlkit/items.py +++ b/tomlkit/items.py @@ -375,14 +375,13 @@ class SingleKey(Key): def __init__( self, - k: str | int, + k: str, t: KeyType | None = None, sep: str | None = None, original: str | None = None, ) -> None: - # keys are allowed to be ints but should be interpreted as strings if not isinstance(k, str): - k = str(k) + raise TypeError("Keys must be strings") if t is None: if not k or any(