![]() |
Applications config files / Best practices - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Applications config files / Best practices (/thread-43426.html) |
Applications config files / Best practices - aecordoba - Oct-22-2024 Hi there! I' m newbie in Python applications development. I'm coding an application that has several modules and I'm looking for the best way to access the configuration file (YAML) from each module without having to read it every time. Can anybody help me? Thank you in advance. -- Adrián E. Córdoba RE: Applications config files / Best practices - DeaD_EyE - Oct-22-2024 If its a user config, save the YAML file in ~/.config/APPNAME/config.yaml and on Windows in %localappdata%\APPNAME\config.yaml .To get the home path, use pathlib. Example for Linux and Windows in one function: import os import platform from pathlib import Path import yaml def load_config(appname): system = platform.system() if system == "Windows": config = Path.home().joinpath( os.environ.get("localappdata"), appname, "config.yaml" ) elif system == "Linux": config = Path.home().joinpath(".config", appname, "config.yaml") else: raise RuntimeError(f"{system} is not supported.") with config.open() as fd: return yaml.load(fd, yaml.SafeLoader) config = load_config("YourAppName")If it should belong to your module and is not a user config, just use a Python file, place it next to your modules and import it, where you need the config. Then yaml is not required. A dependency lesser is good. RE: Applications config files / Best practices - aecordoba - Oct-23-2024 (Oct-22-2024, 07:30 PM)DeaD_EyE Wrote: If it should belong to your module and is not a user config, just use a Python file, place it next to your modules and import it, where you need the config. Then yaml is not required. A dependency lesser is good.Thank you very much, DeaD_EyE! |