Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BUGFIX] Fix Context initialization with another Context object #160

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 14 additions & 9 deletions src/koheesio/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ def __init__(self, *args, **kwargs): # type: ignore[no-untyped-def]
if isinstance(arg, dict):
kwargs.update(arg)
if isinstance(arg, Context):
kwargs = kwargs.update(arg.to_dict())
kwargs.update(arg.to_dict())

if kwargs:
for key, value in kwargs.items():
Expand Down Expand Up @@ -337,15 +337,20 @@ def get(self, key: str, default: Any = None, safe: bool = True) -> Any:
Returns `c`
"""
try:
if "." not in key:
# in case key is directly available, or is written in dotted notation
try:
return self.__dict__[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
except KeyError:
pass
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
27 changes: 27 additions & 0 deletions tests/core/test_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,18 @@ def test_contains():
# recursive
True,
),
(
# Test Context initialization with another Context object
# ---
# left_context
Context({"foo": "bar"}),
# right_context
Context(Context({"baz": "qux"})),
# expected
{"foo": "bar", "baz": "qux"},
# recursive
None,
),
],
)
def test_merge(left_context, right_context, expected, recursive):
Expand Down Expand Up @@ -212,6 +224,21 @@ def test_from_dict():
"c": [{"d": 2, "e": "nested"}, 1, "test2", False, {"f": 2, "g": [{"d": 2, "e": "nested"}, 1, "test3"]}],
},
),
(
# Test Context initialization with another Context object
Context(Context({"baz": "qux"})),
{"baz": "qux"},
),
(
# Test with just kwargs
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