pyYAML Errors on “!” in a string

≡放荡痞女 提交于 2019-11-28 10:59:16
kichik

Exclamation mark is a prefix for YAML tags. The parser has to implement a constructor for it by the tag name. There are some default tags like !!bool, !!int, etc. and even some Python specific tags like !!python/tuple.

You can define your own constructors and even constructors for multiple tags caught by a prefix. By defining the prefix to '', you can catch all the tags and ignore them. You can return the tag and its value from the constructor to just treat it all as text.

>>> import yaml
>>> def default_ctor(loader, tag_suffix, node):
...     print loader
...     print tag_suffix
...     print node
...     return tag_suffix + ' ' + node.value
...
>>> yaml.add_multi_constructor('', default_ctor)
>>> yaml.load(y)
<yaml.loader.Loader object at 0xb76ce8ec>
!$uzy
ScalarNode(tag=u'!$uzy', value=u'')
{'world': {'people': {'name': '!$uzy', 'address': 'chez-bob'}}}
>>>

If a value starts with "!", you must enclose the value in single or double quotes; otherwise it is interpreted as a YAML tag.

world:
     people:
          name: "!$uzy"
          address: chez-bob

This is actually a bug in PyYAML. It interprets the : in name:!$uzy as a key/value separator, but it should only do so if : is followed by a space, or if the preceding scalar (name) is quoted. The follow up error is that the exclamation mark, which should be allowed in the middle of a scalar, gets incorrectly interpreted as being at the beginning of a scalar and hence introducing a tag.

The value for key people is the string name:!$uzy address:chez-bob and that is handled correctly in other parsers (including the Python package ruamel.yaml of which I am the author).

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!