From 1e2f6ce60cf0c6bb622319e3904acfbac37f3b72 Mon Sep 17 00:00:00 2001 From: Aaron LI Date: Sun, 2 Oct 2016 15:30:32 +0800 Subject: configs/manager.py: Add "getn()" method to get multi-level config value --- fg21sim/configs/manager.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) (limited to 'fg21sim') diff --git a/fg21sim/configs/manager.py b/fg21sim/configs/manager.py index eabff00..e274609 100644 --- a/fg21sim/configs/manager.py +++ b/fg21sim/configs/manager.py @@ -13,6 +13,7 @@ import os import sys from glob import glob import logging +from functools import reduce from configobj import ConfigObj, ConfigObjError, flatten_errors from validate import Validator @@ -93,6 +94,30 @@ class ConfigManager: """Get config value by key.""" return self._config.get(key, fallback) + def getn(self, keys, sep="/"): + """Get the config value from the nested dictionary configs using + a list of keys or a "sep"-separated keys strings. + + Parameters + ---------- + keys : str / list[str] + List of keys or a string separated by a specific character + (e.g., "/") to specify the item in the `self._config`, which + is a nested dictionary. + e.g., `["section1", "key2"]`, `"section1/key2"` + sep : str (len=1) + If the above "keys" is a string, then this parameter specify + the character used to separate the multi-level keys. + + References + ---------- + - Stackoverflow: Checking a Dictionary using a dot notation string + https://stackoverflow.com/q/12414821/4856091 + """ + if isinstance(keys, str): + keys = keys.split(sep) + return reduce(dict.get, keys, self._config) + @property def logging(self): """Get and prepare the logging configurations for -- cgit v1.2.2