Skip to content

Commit

Permalink
added utility function to get an item from a nested dict
Browse files Browse the repository at this point in the history
this was initially part of elastic#1321
  • Loading branch information
beniwohli committed Oct 13, 2021
1 parent 4eb8be5 commit 4bbb521
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
10 changes: 10 additions & 0 deletions elasticapm/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,3 +193,13 @@ def starmatch_to_regex(pattern):
else:
res.append(re.escape(c))
return re.compile(r"(?:%s)\Z" % "".join(res), options)


def nested_key(d: dict, *args):
for arg in args:
try:
d = d[arg]
except (TypeError, KeyError):
d = None
break
return d
20 changes: 20 additions & 0 deletions tests/utils/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
from elasticapm.utils import (
get_name_from_func,
get_url_dict,
nested_key,
read_pem_file,
sanitize_url,
starmatch_to_regex,
Expand Down Expand Up @@ -240,3 +241,22 @@ def test_read_pem_file_chain():
with open(os.path.join(os.path.dirname(__file__), "..", "ca", "chain.crt"), mode="rb") as f:
result = read_pem_file(f)
assert result.endswith(b"\xc8\xae")


@pytest.mark.parametrize(
"data,key,expected",
[
(None, "x", None),
({}, "x", None),
({"x": 1}, "x", 1),
({"x": {"y": 1}}, "x.y", 1),
({"x": 1}, "x.y", None),
({"x": {"y": {}}}, "x.y.z", None),
],
)
def test_nested_key(data, key, expected):
r = nested_key(data, *key.split("."))
if expected is None:
assert r is expected
else:
assert r == expected

0 comments on commit 4bbb521

Please sign in to comment.