简体   繁体   中英

Have a function or class to store local variables that are parsed from yaml file in Python

I have a few lines of code that will open a yaml file and parse some values and store them in local variables in PYTHON.

config.yml:

mysql:
  host: localhost
  database: myDatabase
  user: root
  password: root

and my code so far:

import yaml
with open("config.yml", 'r') as ymlfile:
cfg = yaml.load(ymlfile)

host = cfg["mysql"]["host"]
database = cfg["mysql"]["database"]
user = cfg["mysql"]["user"]
password = cfg["mysql"]["password"]

I was wondering if there is a way I can store this in a neat function, and more importantly, call each variable from another function.

Something like:

def parse_config():
    <code> 

def main():
    password = parse_config() 

Also, would it be better to have this in a SEPERATE class?

You can write this as a class and then you don't need to access the file every time.


import yaml

class MyYaml():

    def __init__(self):
        with open("config.yml", 'r') as ymlfile:
            cfg = yaml.load(ymlfile)

            self.host = cfg["mysql"]["host"]
            self.database = cfg["mysql"]["database"]
            self.user = cfg["mysql"]["user"]
            self.password = cfg["mysql"]["password"]

my_yaml = MyYaml()

print(my_yaml.host)
print(my_yaml.database)

In this case, you will access the file every time.

def parse_config(param: str):
    with open("config.yml", 'r') as ymlfile:
        cfg = yaml.load(ymlfile)
        return(cfg["mysql"][param])

password = parse_config("password")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM