Skip to content

Commit 78a3484

Browse files
committed
Add utility to access configuration value by path
At getting the value in nested settings dict, newly added get_config_by_path() is more efficient and readable than "get with empty dict" chain like below, which is sometimes used in current implementation. settings.get("foo", {}).get("bar", {}).get("baz")
1 parent 358a829 commit 78a3484

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

pyls/_utils.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,25 @@ def _merge_dicts_(a, b):
132132
return dict(_merge_dicts_(dict_a, dict_b))
133133

134134

135+
def get_config_by_path(settings, path, default_value=None):
136+
"""Get the value in settings dict at the given path.
137+
138+
If path is not resolvable in specified settings, this returns
139+
default_value.
140+
"""
141+
paths = path.split('.')
142+
while len(paths) > 1:
143+
settings = settings.get(paths.pop(0))
144+
if not isinstance(settings, dict):
145+
# Here, at least one more looking up should be available,
146+
# but the last retrieved was non-dict. Therefore, path is
147+
# not resolvable in specified settings.
148+
return default_value
149+
150+
# Here, paths should have only one value
151+
return settings.get(paths[0], default_value)
152+
153+
135154
def format_docstring(contents):
136155
"""Python doc strings come in a number of formats, but LSP wants markdown.
137156

0 commit comments

Comments
 (0)