aboutsummaryrefslogtreecommitdiffstats
path: root/config_file
diff options
context:
space:
mode:
Diffstat (limited to 'config_file')
-rw-r--r--config_file/config_file.py10
-rw-r--r--config_file/parsers/json_parser.py13
2 files changed, 19 insertions, 4 deletions
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]