招摇占位符如何运作?

时间:2016-06-12 06:51:34

标签: express yaml swagger

我加入了一个使用Swagger的项目。我看到他们在Swagger.yaml

中使用了这种占位符
  MYKey: &CONST_MY_KEY ""

这是如何工作的?我在哪里定义CONST_MY_KEY

2 个答案:

答案 0 :(得分:1)

这是一个称为锚点的YAML构造,并不特定于招摇。

您编写的代码实际上将锚CONST_MY_KEY定义为空字符串。 & - 前缀表示您正在定义它。如果您希望稍后在文档中重复使用此锚点,则可以使用* - 前缀来引用它,而不是*CONST_MY_KEY

以下是https://learnxinyminutes.com/docs/yaml/的解释摘录:

# YAML also has a handy feature called 'anchors', which let you easily duplicate
# content across your document. Both of these keys will have the same value:
anchored_content: &anchor_name This string will appear as the value of two keys.
other_anchor: *anchor_name

# Anchors can be used to duplicate/inherit properties
base: &base
    name: Everyone has same name

foo: &foo
  <<: *base
  age: 10

bar: &bar
  <<: *base
  age: 20

答案 1 :(得分:1)

您没有在任何地方定义CONST_MY_KEY&会将此作为对象""的锚点引入。您可以在YAML文件的后续阶段重复使用此操作,方法是使用*指定别名:*CONST_MY_KEY

锚点和别名的主要原因是来复制内容,如@smartcaveman的答案所示。它是represent a node in multiple locations in the representation graph

如果没有此功能,则无法转储以下简单的Python构造:

data = dict(a=1)
data['b'] = data

如果您转储上述内容:

import sys
import ruamel.yaml

ruamel.yaml.round_trip_dump(data, sys.stdout)

你会得到:

&id001
a: 1
b: *id001

根据您使用的语言及其YAML解析器,在标量上使用锚点,可能仅对以后不必重复该值有用,而没有您使用集合(映射,序列)实际获得的优势引用同一个对象。同样在Python中,更流行的解析器加载标量是在不同的实体中完成的:

import ruamel.yaml

yaml_str = """\
a: &CONST_MY_KEY ""
b: *CONST_MY_KEY
"""

data = ruamel.yaml.round_trip_load(yaml_str)
print('a {a!r}'.format(**data))
print('b {b!r}'.format(**data))
data['a'] = 'hello'
print('a {a!r}'.format(**data))
print('b {b!r}'.format(**data))

给你:

a ''
b ''
a 'hello'
b ''

请注意,data['b']的值不会更改,因为(在大多数解析器中)标量不会构造为引用对象。

如果您使用原始示例执行此操作:

import ruamel.yaml

yaml_str = """\
&id001
b: *id001
a: 1
"""

data = ruamel.yaml.round_trip_load(yaml_str)
print('a {a!r}'.format(**data))
data['b']['a'] = 2
print('a {a!r}'.format(**data))

因为data['a']data['b']['a']实际上是同一个对象,而更改一个会改变另一个。

<<: *name的使用是非标准的YAML扩展。它期望&name成为映射的锚点,为此,键值对将添加到使用别名的映射中。

相关问题