toml.TomlPreserveInlineDictEncoder() 是如何工作的?

问题描述 投票:0回答:1

我查看了 toml 库源代码,我想我明白这个编码器应该在一行中格式化字典,而不是经典的字典 toml 格式。
我的预期行为如下:

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}

但是,事实上,更改编码器不会对转储的字符串进行任何更改。 (我也尝试过使用嵌套字典)

我错过了什么吗?这个功能应该有效吗?
(我在Python 3.8和3.10中测试过)

python python-3.x toml
1个回答
0
投票

toml.TomlPreserveInlineDictEncoder
旨在保留由
toml
自己的解码器解析时最初内联格式化的字典的格式。

例如:

import toml

data = toml.loads('''\
A = {a = 1, b = 2, c = 3}
B = {a = 1, b = 2, c = 3}
''')

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

# TomlPreserveInlineDictEncoder
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 }
© www.soinside.com 2019 - 2024. All rights reserved.