From 5fa867ba5a2e0927e9b87a8228989357924623d2 Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Sun, 9 Feb 2020 13:54:09 -0600 Subject: Allow a default value for the get() method --- config_file/config_file.py | 10 ++++++++-- config_file/parsers/json_parser.py | 13 +++++++++++-- 2 files changed, 19 insertions(+), 4 deletions(-) (limited to 'config_file') diff --git a/config_file/config_file.py b/config_file/config_file.py index d9f9a2e..524272c 100644 --- a/config_file/config_file.py +++ b/config_file/config_file.py @@ -2,7 +2,7 @@ import inspect from pathlib import Path, PurePath from shutil import copyfile -from config_file.parsers.base_parser import BaseParser +from config_file.parsers.base_parser import BaseParser, ParsingError from config_file.parsers.ini_parser import IniParser from config_file.parsers.json_parser import JsonParser from config_file.utils import split_on_dot @@ -66,7 +66,7 @@ class ConfigFile: with open(self.path, "r") as file: return file.read() - def get(self, key: str, parse_type: bool = True): + def get(self, key: str, parse_type: bool = True, default=None): """ Retrieve the value of a key in its native type. This means the string 'true' will be parsed back as the @@ -75,6 +75,12 @@ class ConfigFile: If parse_type is set to False, all values will be returned back as strings. """ + if default is not None: + try: + return self.parser.get(key, parse_type=parse_type) + except ParsingError: + return default + return self.parser.get(key, parse_type=parse_type) def set(self, key: str, value): diff --git a/config_file/parsers/json_parser.py b/config_file/parsers/json_parser.py index 8e4617b..9b8e93c 100644 --- a/config_file/parsers/json_parser.py +++ b/config_file/parsers/json_parser.py @@ -76,8 +76,17 @@ class JsonParser(BaseParser): elif "." in key: split_keys = split_on_dot(key) result = self.parsed_content - for key in split_keys: - result = result[key] + + # Used so we can more precisely specify what key is causing the error. + key_for_error = None + try: + for key in split_keys: + key_for_error = key + result = result[key] + except TypeError: + raise ParsingError( + f"Cannot get {key} because {key_for_error} is not subscriptable." + ) else: result = self.parsed_content[key] -- cgit v1.2.3