python - 如何在 Python 中验证字典的结构(或模式)?

标签 python validation dictionary schema config

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

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 更容易实现的库?

最佳答案

您可以使用 schema (PyPi Link)

schema is a library for validating Python data structures, such as those obtained from config-files, forms, external services or command-line parsing, converted from JSON/YAML (or something else) to Python data-types.

from schema import Schema, And, Use, Optional, SchemaError

def check(conf_schema, conf):
    try:
        conf_schema.validate(conf)
        return True
    except SchemaError:
        return False

conf_schema = Schema({
    'version': And(Use(int)),
    'info': {
        'conf_one': And(Use(float)),
        'conf_two': And(Use(str)),
        'conf_three': And(Use(bool)),
        Optional('optional_conf'): And(Use(str))
    }
})

conf = {
    'version': 1,
    'info': {
        'conf_one': 2.5,
        'conf_two': 'foo',
        'conf_three': False,
        'optional_conf': 'bar'
    }
}

print(check(conf_schema, conf))

关于python - 如何在 Python 中验证字典的结构(或模式)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45812387/

相关文章:

python - 如何在 Numpy 中取 long 的对数

用于手机号码验证的正则表达式

c++ - 我可以使用 map<char[2],class> 中的类类型作为容器吗?

python - 如何在 Matplotlib 中旋转表头?

python - 改进 MySQLdb 查询

c# - 在 MVC 中加载页面时是否可以显示验证错误 - 4(使用模型验证)

python - 将字典打印到表格中

python - 在字典中存储 lambda

python - 使用 DEAP 进行遗传规划(最大化问题)时,群体平均适应度下降是否正常?

java - 跳过 build.xml 的 Eclipse 验证