Home >Backend Development >Python Tutorial >pyya - The way to manage YAML config in your Python project
Imagine you have a file like this in your project:
# config.yaml database: host: localhost port: 5432 username: postgres password: postgres
To parse this dot yaml configuration file in Python you usually do this:
import yaml # pip install PyYAML with open("config.yaml", encoding='utf-8') as fstream: config_yaml = yaml.safe_load(fstream)
To create Javascript-like objects from resulting dictionary you probably add the following:
from munch import munchify # pip install munch config = munchify(config_yaml)
pyya does that automatically with one function:
from pyya import init_config config = init_config( 'config.yaml', 'default.config.yaml', merge_configs = False, convert_keys_to_snake_case = False, add_underscore_prefix_to_keywords = False raise_error_non_identifiers = False) print(config.database) # Output: # Munch({"host": "localhost", "port": 5432, "username": "postgres", "password": "postgres"})
What about all these flags?
merge_configs if set to True, compares config.yaml with default.config.yaml (or whatever names or paths you specify) and adds to the former all the fields that are not present in the latter. If set to False disables all merging and all formatting done by the rest of the flags.
convert_keys_to_snake_case is kinda self-explanatory because it simply makes configuration keys look pythonic. However, this flag may break some settings like logging configuration.
add_underscore_prefix_to_keywords if configuration key is also Python keyword, it will add underscore in front of it (class becomes _class). It allows attribute access work better.
raise_error_non_identifiers if configuration key is also non-valid Python identificator, it will raise error.
You can install pyya like this:
pip install pyya
Contributions and suggestions are welcome: https://github.com/shadowy-pycoder/pyya
The above is the detailed content of pyya - The way to manage YAML config in your Python project. For more information, please follow other related articles on the PHP Chinese website!