Python function-Bunch configuration loading

0 Foreword###

In Python development, configuration files are often written in files in the form of json
Bunch can convert configuration files into configuration classes and configuration dictionaries.

1 Bunch tutorial##

1.1 initialization###

>>> 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 Inherit the usage of 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 Serialization###

>>> 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.Bunch\nfoo: !bunch.Bunch {lol: true}\nhello: 42\nponies: are pretty!\n'>>> yaml.safe_dump(b)'foo: {lol: true}\nhello: 42\nponies: are pretty!\n'

2 Interface package##

import json
from bunch import Bunch

def get_config_from_json(json_file):"""
 Convert configuration files to configuration classes
 : param json_file:json file
 : return:Configuration information
    """
 withopen(json_file,'r')as config_file:
  config_dict = json.load(config_file)  #Configuration dictionary
 config =Bunch(config_dict)  #Convert configuration dictionary to class
 return config, config_dict
  1. https://juejin.im/post/5aded5b7518825671b022c18

  2. https://pypi.org/project/bunch/

Recommended Posts

Python function-Bunch configuration loading
ubuntu configuration python, Red
Python3 configuration and entry.md
How to write python configuration file