如何使自定义 YAML 标记与 pyyaml 中的序列别名一起使用 [英] How to make a custom YAML tag work with a sequence alias in pyyaml

查看:55
本文介绍了如何使自定义 YAML 标记与 pyyaml 中的序列别名一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有这样别名的 yaml 文件:

I’ve got a yaml file with aliases like this:

vars:
  users: &users ['user1', 'user2', 'user3', 'user4']

refs:
  users: *users
  user: !rand ['user1', 'user2', 'user3', 'user4']

!rand 是一个自定义标签,它在 yaml 序列上调用 python 的 random.choice.

!rand is a custom tag that calls python’s random.choice on a yaml sequence.

我正在使用 !rand 标签的以下实现:

I’m using the following implementation of the !rand tag:

import random
import yaml

def load_yaml(file):
    def rand_constructor(loader, node):
        value = loader.construct_sequence(node)
        return random.choice(value)

    yaml.add_constructor('!rand', rand_constructor)

    with open(file) as f:
        return yaml.load(f)

它按预期工作,并且 userusers 获得一个随机值.现在,当我使用带有别名 *users!rand 时,它停止工作:

It works as expected, and user gets a random value from users. Now, when I use !rand with the alias *users it stops working:

vars:
  users: &users ['user1', 'user2', 'user3', 'user4']

refs:
  users: *users
  user: !rand *users

错误是:

File ../python3.6/site-packages/yaml/parser.py", line 439, in parse_block_mapping_key
    "expected <block end>, but found %r" % token.id, token.start_mark)
yaml.parser.ParserError: while parsing a block mapping
  in "/temp/config.yml", line 5, column 3
expected <block end>, but found '<alias>'
  in "/temp/config.yml", line 6, column 18

如何使其与序列别名一起使用?

How do I make it work with sequence aliases?

推荐答案

你也可以让你的列表可调用,并在每次需要随机用户时调用它:

You can also make your list callable and call it each time you need random user:

YAML = """
user: &users !rand 
    - user1
    - user2
    - user3
    - user4
"""

import random
import yaml
from collections.abc import Sequence

class RandomizableList(Sequence):
    def __init__(self, items):
        self.items = items
    def __len__(self):
        return len(self.items)
    def __getitem__(self, value):
        return self.items[value]
    def __call__(self):
        return random.choice(self.items)
    def __repr__(self):
        return repr(self.items)

def rand_constructor(loader, node):
    return RandomizableList(loader.construct_sequence(node))

yaml.add_constructor('!rand', rand_constructor)
result = yaml.load(YAML)
for i in range(4):
    print(result['user']())
print(result['user'])

这篇关于如何使自定义 YAML 标记与 pyyaml 中的序列别名一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆