Warm tip: This article is reproduced from serverfault.com, please click

validation-如何在Python中验证字典的结构(或架构)?

(validation - How to validate structure (or schema) of dictionary in Python?)

发布于 2017-08-22 08:17:40

我有一本包含配置信息的字典:

my_conf = {
    'version': 1,

    'info': {
        'conf_one': 2.5,
        'conf_two': 'foo',
        'conf_three': False,
        'optional_conf': 'bar'
    }
}

我想检查字典是否符合我需要的结构。

我正在寻找这样的东西:

conf_structure = {
    'version': int,

    'info': {
        'conf_one': float,
        'conf_two': str,
        'conf_three': bool
    }
}

is_ok = check_structure(conf_structure, my_conf)

有没有针对此问题的解决方案或可以简化实施的任何库check_structure

Questioner
Thyrst'
Viewed
11
tobias_k 2018-04-03 19:33:16

在不使用库的情况下,你还可以定义一个简单的递归函数,如下所示:

def check_structure(struct, conf):
    if isinstance(struct, dict) and isinstance(conf, dict):
        # struct is a dict of types or other dicts
        return all(k in conf and check_structure(struct[k], conf[k]) for k in struct)
    if isinstance(struct, list) and isinstance(conf, list):
        # struct is list in the form [type or dict]
        return all(check_structure(struct[0], c) for c in conf)
    elif isinstance(struct, type):
        # struct is the type of conf
        return isinstance(conf, struct)
    else:
        # struct is neither a dict, nor list, not type
        return False

假设配置可以包含不在你的结构中的键,如你的示例所示。


更新:新版本还支持列表,例如 'foo': [{'bar': int}]