Skip to content

Commit

Permalink
use a default sentinel for .get() so None can be a default
Browse files Browse the repository at this point in the history
  • Loading branch information
pjz committed Oct 11, 2023
1 parent ba1ed7e commit e37953a
Showing 1 changed file with 11 additions and 4 deletions.
15 changes: 11 additions & 4 deletions mincfg/configs.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ def _recursive_dict_update(main: Dict, update: Dict):
main[lk] = v


DEFAULT_SENTINEL = object()


class MergedConfiguration:
"""
Merges configuration sources
Expand Down Expand Up @@ -79,7 +82,7 @@ def as_dict(self, namespace: Optional[List[str]] = None) -> CfgDict:
raise ValueError(f"namespace {'.'.join(ns)} points to a key, not a dict")
return in_ns

def get(self, key: str, namespace: Optional[List[str]]=None, default=None, parser=str, raise_error=True, doc=None):
def get(self, key: str, namespace: Optional[List[str]]=None, default=DEFAULT_SENTINEL, parser=str, raise_error=True, doc=None):
"""
get a single config key
Expand All @@ -95,12 +98,16 @@ def get(self, key: str, namespace: Optional[List[str]]=None, default=None, parse
in_ns = self.as_dict()
for subns in ns:
in_ns = in_ns[subns]
if raise_error and default is None and k not in in_ns:
msg = f"Missing config key {'.'.join(ns + [k])}"
if k in in_ns:
return parser(in_ns.get(k, default))
if default is not DEFAULT_SENTINEL:
return default
if raise_error:
msg = f"Missing config key {'.'.join(ns + [k])!r}"
if doc:
msg += f": {doc}"
raise KeyError(msg)
return parser(in_ns.get(k, default))
return None

def as_ns(self, namespace: Optional[List[str]]=None) -> SimpleNamespace:
"""
Expand Down

0 comments on commit e37953a

Please sign in to comment.