python函数——Bunch配置加载

时间:2022-07-24
本文章向大家介绍python函数——Bunch配置加载,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

0 前言

在Python开发中,经常将配置文件以json 的形式写在文件中 Bunch可以将配置文件转换为配置类和配置字典。

1 Bunch 教程

1.1 初始化

>>> b = Bunch()
>>> b.hello = 'world'
>>> b.hello
'world'
>>> b['hello'] += "!"
>>> b.hello
'world!'
>>> b.foo = Bunch(lol=True)
>>> b.foo.lol
True
>>> b.foo is b['foo']
True

1.2 继承Dict 的使用用法

>>> b.keys()
['foo', 'hello']
>>> b.update({ 'ponies': 'are pretty!' }, hello=42)
>>> print repr(b)
Bunch(foo=Bunch(lol=True), hello=42, ponies='are pretty!')
>>> [ (k,b[k]) for k in b ]
[('ponies', 'are pretty!'), ('foo', Bunch(lol=True)), ('hello', 42)]
>>> "The {knights} who say {ni}!".format(**Bunch(knights='lolcats', ni='can haz'))
'The lolcats who say can haz!'

1.3 序列化

>>> b = Bunch(foo=Bunch(lol=True), hello=42, ponies='are pretty!')
>>> import json
>>> json.dumps(b)
'{"ponies": "are pretty!", "foo": {"lol": true}, "hello": 42}'
>>> b = Bunch(foo=Bunch(lol=True), hello=42, ponies='are pretty!')
>>> import yaml
>>> yaml.dump(b)
'!bunch.Bunchnfoo: !bunch.Bunch {lol: true}nhello: 42nponies: are pretty!n'
>>> yaml.safe_dump(b)
'foo: {lol: true}nhello: 42nponies: are pretty!n'

2 接口封装

import json
from bunch import Bunch

def get_config_from_json(json_file):
    """
    将配置文件转换为配置类
    :param json_file: json文件
    :return: 配置信息
    """
    with open(json_file, 'r') as config_file:
        config_dict = json.load(config_file)  # 配置字典
    config = Bunch(config_dict)  # 将配置字典转换为类
    return config, config_dict
  1. https://juejin.im/post/5aded5b7518825671b022c18
  2. https://pypi.org/project/bunch/