Skip to content

Commit

Permalink
[BUGFIX] Enhance key access in Context class to support direct and ne…
Browse files Browse the repository at this point in the history
…sted dotted notation
  • Loading branch information
dannymeijer committed Jan 29, 2025
1 parent 800d760 commit c515d64
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 8 deletions.
18 changes: 10 additions & 8 deletions src/koheesio/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -337,18 +337,20 @@ def get(self, key: str, default: Any = None, safe: bool = True) -> Any:
Returns `c`
"""
try:
# try full dotted natation first
# in case key is directly available, or is written in dotted notation
try:
return self.__dict__[key]
except KeyError:
pass

# handle nested keys
nested_keys = key.split(".")
value = self # parent object
for k in nested_keys:
value = value[k] # iterate through nested values
return value
if "." in key:
# handle nested keys
nested_keys = key.split(".")
value = self # parent object
for k in nested_keys:
value = value[k] # iterate through nested values
return value

raise KeyError

except (AttributeError, KeyError, TypeError) as e:
if not safe:
Expand Down
5 changes: 5 additions & 0 deletions tests/core/test_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,11 @@ def test_from_dict():
Context(foo="bar", baz="qux"),
{"foo": "bar", "baz": "qux"},
),
(
# Test with dotted keys
Context({"a.b.c": 1}),
{"a.b.c": 1},
)
],
)
def test_to_dict(context, expected):
Expand Down

0 comments on commit c515d64

Please sign in to comment.