Python addict包(像使用属性一样来操作字典)

背景

工作中需要从DB中或者文件中读取配置信息,解析成一个多重嵌套的字典供项目使用。每次取值和更新的时候都比较麻烦,取下标需要捕获KeyError,用get多取几层又觉得不够优雅。

介绍

官方文档:https://github.com/mewwts/addict/blob/master/README.md

字面理解就是高级字典(我猜的,逃),在dict的基础上封装了一层,使其能够像操作属性一样使用字典。使得后续操作更加简便且易读,还可以预防不必要的异常出现。作者打趣说是用完能让你上瘾的好东西(笑)。

下载

pip install addict

基本使用

from addict import Dict

configs = Dict()

configs.platform.status = "on"
configs.platform.web.task.name = "测试-1204"
configs.platform.web.periods.start = "2020-10-01"
configs.platform.web.periods.end = "2020-10-31"

效果如下

task_configs = {
    "status": "on",
    "platform": {
        "web": {
            "task": {
                "name": "测试-1204"
            },
            "periods": {
                "start": "2020-10-01",
                "end": "2020-10-31"
            }
        }
    }
}

获取不存在的key时会返回一个空字典,不用担心报KeyError,对返回值做判空处理即可

app_configs = configs.platform.app
assert app_configs == {}
原文地址:https://www.cnblogs.com/kangyuqi/p/13871693.html