pythonpython-3.xtoml

How does toml.TomlPreserveInlineDictEncoder() work?


I had a look on the toml library source code and I think I understand that this encoder should format dictionaries in one line instead of classic dictionary toml format.

My expected behavior is the following :

import toml

data = {'a': 1, 'b': 2, 'c': 3}

# Default Encoder
toml_string = toml.dumps(data)
print(toml_string)
# Output:
# a = 1
# b = 2
# c = 3

# TomlPreserveInlineDictEncoder
toml_string = toml.dumps(data, encoder=toml.TomlPreserveInlineDictEncoder())
print(toml_string)
# Output:
# {a = 1, b = 2, c = 3}

But, in fact, changing encoder doesn't change anything to the dumped string. (I also tried with nested dictionaries)

Did I miss something ? Is this functionality suppose to work ?
(I tested it in Python 3.8 and 3.10)


Solution

  • toml.TomlPreserveInlineDictEncoder is meant to preserve the formatting of dicts that are originally formatted inline when parsed by toml's own decoder.

    For example:

    import toml
    
    data = toml.loads('''\
    A = {a = 1, b = 2, c = 3}
    B = {a = 1, b = 2, c = 3}
    ''')
    
    toml_string = toml.dumps(data, encoder=toml.TomlPreserveInlineDictEncoder())
    print(toml_string)
    # Output:
    # A = { a = 1, b = 2, c = 3 }
    # B = { a = 1, b = 2, c = 3 }
    

    Since toml's encoder determines if a dict should be formatted inline by checking if the dict is an instance of toml.decoder.InlineTableDict, you can manually format a section of the dict as inline with a subclass of dict and InlineTableDict:

    import toml
    
    class InlineDict(dict, toml.decoder.InlineTableDict):
        pass
    
    data = {'A': InlineDict({'a': 1, 'b': 2, 'c': 3})}
    
    toml_string = toml.dumps(data, encoder=toml.TomlPreserveInlineDictEncoder())
    print(toml_string)
    # Output:
    # A = { a = 1, b = 2, c = 3 }