Reading YAML config file in python and using variables -


say have yaml config file such as:

test1:     minvolt: -1     maxvolt: 1 test2:     curr: 5     volt: 5 

i can read file python using:

import yaml  open("config.yaml", "r") f:     config = yaml.load(f) 

then can access variables

config['test1']['minvolt'] 

style-wise, best way use variables config file? using variables in multiple modules. if access variables shown above, if renamed, need rename every instance of variable.

just wondering best or common practices using variables config file in different modules.

you can this:

class test1class:     def __init__(self, raw):         self.minvolt = raw['minvolt']         self.maxvolt = raw['maxvolt']  class test2class:     def __init__(self, raw):         self.curr = raw['curr']         self.volt = raw['volt']  class config:     def __init__(self, raw):         self.test1 = test1class(raw['test1'])         self.test2 = test2class(raw['test2'])  config = config(yaml.safe_load(""" test1:     minvolt: -1     maxvolt: 1 test2:     curr: 5     volt: 5 """)) 

and access values with:

config.test1.minvolt 

when rename values in yaml file, need change classes @ 1 place.

note: pyyaml allows directly deserialize yaml custom classes. however, work, you'd need add tags yaml file pyyaml knows classes deserialize to. expect not want make yaml input more complex.


Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -