toml icon indicating copy to clipboard operation
toml copied to clipboard

cannot encode non-string keys

Open jesteria opened this issue 2 years ago • 1 comments

The library appears unable to encode dictionaries with non-string, e.g. integer, keys. This is the case at the top level and inline.

For example, using master (59d83d0d51a976f11a74991fa7d220fc630d8bae):

$ python3
Python 3.10.4 (main, Jun 29 2022, 12:14:53) [GCC 11.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import toml
>>> toml.__file__
'/PATH/TO/REPO/toml/toml/__init__.py'
>>> toml.__version__
'0.10.2'
>>> toml.dumps({1: 'a'})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/PATH/TO/REPO/toml/toml/encoder.py", line 60, in dumps
    addtoretval, sections = encoder.dump_sections(o, "")
  File "/PATH/TO/REPO/toml/toml/encoder.py", line 193, in dump_sections
    if not isinstance(o[section], dict):
KeyError: '1'
>>> toml.TomlEncoder().dump_inline_table({'1': {1: 'a'}})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/PATH/TO/REPO/toml/toml/encoder.py", line 167, in dump_inline_table
    val = self.dump_inline_table(v)
  File "/PATH/TO/REPO/toml/toml/encoder.py", line 168, in dump_inline_table
    val_list.append(k + " = " + val)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

jesteria avatar Nov 17 '22 21:11 jesteria

Bah, I see now that in this example the integer is intended to be interpreted as a string, i.e. keys are only strings [spec].

In that case this handling is not unreasonable. It might make sense to catch and raise an error or cast to string … but that's another matter.

jesteria avatar Nov 17 '22 21:11 jesteria