configuration

This module allows the parsing of YAML config files into a python dict.

To load a YAML file located in config/ use the method from_name:

config = configuration.from_name("example.yml")

Access the information of the YAML file by accessing members of the returned object. E.g. if the YAML file has an entry "seed: 1234":

print(config["seed"])
1234

You can also load from a relative or absolute file path:

config_relative = configuration.from_rel_path("../example.yml")
config_absolute = configuration.from_abs_path("/home/user/config/example.yml")

Save the current configuration to config/ using the save_to_file method:

save_to_file(config) # Uses current time as filename
save_to_file(config,"example.yaml") 
 1"""
 2.. include:: ../docs/configuration.md
 3"""
 4
 5import datetime
 6import os
 7import os.path
 8from os.path import isabs
 9from typing import Dict, Optional
10
11import yaml
12
13configDir = os.path.join(os.path.dirname(__file__), "..", "config")
14if not os.path.isdir(configDir):
15    os.makedirs(configDir,exist_ok=True)
16
17
18def save_to_file(configuration: Dict, configName: Optional[str] = None):
19    """
20    If a `configName` is passed, this will be used to construct the file
21    name. Otherwise the current time is used. Either way, config files are
22    written into the `config/` directory.
23    """
24    if configName is None:
25        now = datetime.datetime.now().strftime("%d.%m.%Y_%H:%M")
26        configName = f"{now}.yml"
27    configFilePath = os.path.join(configDir, configName)
28    with open(configFilePath, 'w') as file:
29        yaml.dump(configuration, file)
30    print(f"Configuration has been saved to {configFilePath}.")
31
32
33def from_abs_path(absoluteFilePath: str) -> Dict:
34    """
35    Load a Configuration from absolute file path.
36    """
37    assert os.path.isfile(
38        absoluteFilePath), f"{absoluteFilePath} not found"
39    with open(absoluteFilePath) as yamlFile:
40        yamlContent: Dict = yaml.load(yamlFile, Loader=yaml.Loader)
41    return yamlContent
42
43
44def from_rel_path(fileName: str) -> Dict:
45    """
46    Load a Configuration from relative file path.
47    """
48    curDir = os.path.abspath(os.path.curdir)
49    absoluteFilePath = os.path.join(curDir, fileName)
50    return from_abs_path(absoluteFilePath)
51
52
53def from_name(fileName: str) -> Dict:
54    """
55    Load a Configuration from `config/`.
56
57    `fileName` is the name of the file inside `config/`.
58    """
59    absoluteFilePath = os.path.join(configDir, fileName)
60    return from_abs_path(absoluteFilePath)
61
62
63def from_cli_options(options: Dict) -> Dict:
64    """
65    Take options from CLI and load correct config file.
66    """
67    configFile = options["config"]
68    try:
69        if isabs(configFile):
70            config = from_abs_path(configFile)
71        else:
72            config = from_rel_path(configFile)
73        name = config["name"]
74        print(f"Using configuration \"{name}\"")
75    except BaseException:
76        config = from_name("example.yml")
77        print("Using default configuration.")
78
79    return config
80
81
82if __name__ == "__main__":
83    import argparse
84    parser = argparse.ArgumentParser(description='Dry run of parsing the provided configuration file.')
85    parser.add_argument('--config', help='Relative path to config file.',)
86    config = from_cli_options(vars(parser.parse_args()))
87    print(config)
def save_to_file(configuration: Dict, configName: Optional[str] = None):
19def save_to_file(configuration: Dict, configName: Optional[str] = None):
20    """
21    If a `configName` is passed, this will be used to construct the file
22    name. Otherwise the current time is used. Either way, config files are
23    written into the `config/` directory.
24    """
25    if configName is None:
26        now = datetime.datetime.now().strftime("%d.%m.%Y_%H:%M")
27        configName = f"{now}.yml"
28    configFilePath = os.path.join(configDir, configName)
29    with open(configFilePath, 'w') as file:
30        yaml.dump(configuration, file)
31    print(f"Configuration has been saved to {configFilePath}.")

If a configName is passed, this will be used to construct the file name. Otherwise the current time is used. Either way, config files are written into the config/ directory.

def from_abs_path(absoluteFilePath: str) -> Dict:
34def from_abs_path(absoluteFilePath: str) -> Dict:
35    """
36    Load a Configuration from absolute file path.
37    """
38    assert os.path.isfile(
39        absoluteFilePath), f"{absoluteFilePath} not found"
40    with open(absoluteFilePath) as yamlFile:
41        yamlContent: Dict = yaml.load(yamlFile, Loader=yaml.Loader)
42    return yamlContent

Load a Configuration from absolute file path.

def from_rel_path(fileName: str) -> Dict:
45def from_rel_path(fileName: str) -> Dict:
46    """
47    Load a Configuration from relative file path.
48    """
49    curDir = os.path.abspath(os.path.curdir)
50    absoluteFilePath = os.path.join(curDir, fileName)
51    return from_abs_path(absoluteFilePath)

Load a Configuration from relative file path.

def from_name(fileName: str) -> Dict:
54def from_name(fileName: str) -> Dict:
55    """
56    Load a Configuration from `config/`.
57
58    `fileName` is the name of the file inside `config/`.
59    """
60    absoluteFilePath = os.path.join(configDir, fileName)
61    return from_abs_path(absoluteFilePath)

Load a Configuration from config/.

fileName is the name of the file inside config/.

def from_cli_options(options: Dict) -> Dict:
64def from_cli_options(options: Dict) -> Dict:
65    """
66    Take options from CLI and load correct config file.
67    """
68    configFile = options["config"]
69    try:
70        if isabs(configFile):
71            config = from_abs_path(configFile)
72        else:
73            config = from_rel_path(configFile)
74        name = config["name"]
75        print(f"Using configuration \"{name}\"")
76    except BaseException:
77        config = from_name("example.yml")
78        print("Using default configuration.")
79
80    return config

Take options from CLI and load correct config file.