[英]ConfigObj and single element lists
I've been looking at ConfigObj and I've run into a problem with validation and single element lists. 我一直在查看ConfigObj,并且遇到了验证和单个元素列表的问题。 Say I have a config specification that looks like the following:
说我有一个配置规范,如下所示:
config_specification = """[Data]
[[__many__]]
type = option('sense.xml')
transport = string
sensors = list
[[[Identifier]]]
type = option("name", "mac", "uuid")
adapter = string(default='')
name = string(default='')
file = string(default='')"""
Now that list can actually just be one element, or more than one. 现在,该列表实际上可以只是一个元素,也可以是多个元素。 I can do more than one easily:
我可以轻松完成多个任务:
[Data]
[[primary]]
type = sense.xml
transport = $http
sensors = $virtual, $gpio, $adc
[[[Identifier]]]
type = name
name = VirtualRelay01
But the following is invalid. 但是以下无效。 It won't convert it to a list of 1:
它不会将其转换为1的列表:
sensors = $virtual
I've tried a couple of variations. 我尝试了几种变体。 This one doesn't work
这个不起作用
sensors = {$virtual}
Neither does this one: 这也不是:
sensors = [$virtual]
And if I do this, it gives me a list with two elements! 如果执行此操作,它将为我提供包含两个元素的列表! One the empty string:
一个空字符串:
sensors = ($virtual,)
I have several of these sections and I've got them in a for loop. 我有几个这样的部分,并且已经将它们放在for循环中。 I apply them to classes that only take lists and I don't want to have to individually code all the special cases to add a list around those (not to mention, it fails validation).
我将它们应用于仅包含列表的类,并且我不想单独编写所有特殊情况以在这些特殊情况附近添加列表(更不用说,它无法通过验证)。
For completeness, here is how I validate things: 为了完整起见,这是我验证方式:
cfg = ConfigObj(filename, configspec=config_specification.split('\n'))
test = cfg.validate(Validator())
valid = True
for (section_list, key, _) in flatten_errors(cfg, test):
if key is not None:
print('Invalid value for key {0} in section {1}'.format(key,', '.join(section_list)))
valid = False
else:
print('Section {0} failed validation'.format(', '.join(section_list)))
valid = False
if not valid:
exit(3)
I'm one of the current configobj developers. 我是当前的configobj开发人员之一。 According to this unit test line , I'd expect
sensors = $virtual,
to work the way you'd expect. 根据此单元测试行 ,我希望
sensors = $virtual,
以您期望的方式工作。
I'm not sure how I feel about ($virtual,)
returning a two-element list. 我不确定返回
($virtual,)
两个元素的列表时的感觉($virtual,)
。 That seems wrong. 好像错了 Probably worth opening an issue unless you can imagine a scenario where you actually anticipate wanting the implicit empty-string.
除非您可以想象一个实际可能需要隐式空字符串的情况,否则可能值得提出一个问题。
根据文档 ,如果您仍然想要一个字符串,则对于您的configspec,您可以只使用sensors = force_list()
,然后在单个元素列表的末尾不需要怪异的逗号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.