使用已定义键和自定义键验证器进行映射 (Map)

实验性

此功能处于 Alpha 阶段。API 可能会在次要版本增量中发生更改。

典型的映射,除了键值由验证器提供的值确定。

YAML 片段示例

Name: United Kingdom
country-code: GB
DIAL CODE: +44
official languages:
- English
- Welsh
from collections import OrderedDict
from strictyaml import Map, Optional, Str, Seq, load, ScalarValidator
from ensure import Ensure

# This example uses slugify from the "python-slugify" package
from slugify import slugify

class Slug(ScalarValidator):
    def validate_scalar(self, chunk):
        return slugify(unicode(chunk.contents))

schema = Map({
    "name": Str(),
    Optional("country-code"): Str(),
    "dial-code": Str(),
    "official-languages": Seq(Str())
}, key_validator=Slug())
Ensure(load(yaml_snippet, schema).data).equals(
    {
        "name": "United Kingdom",
        "country-code": "GB",
        "dial-code": "+44",
        "official-languages": ["English", "Welsh"],
    }
)

可执行规范

map-with-key-validator.story storytests 自动生成的文档。