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

make Cut implicitly inherit an "object" #32

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
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
15 changes: 9 additions & 6 deletions scalpl/scalpl.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,13 +61,15 @@ def split_path(path: str, key_separator: str) -> TKeyList:
"you can only provide integers to access list items."
)
else:
raise ValueError(f"Key '{section}' is badly formated.")
raise ValueError(f"Key '{section}' is badly formatted.")

return result


def traverse(data: dict, keys: List[Union[str, int]], original_path: str):
value = data
#: unlikely, but `key` can be referenced before assignment.
key = None
try:
for key in keys:
value = value[key]
Expand All @@ -81,12 +83,12 @@ def traverse(data: dict, keys: List[Union[str, int]], original_path: str):
return value


class Cut:
class Cut(object):
"""
Cut is a simple wrapper over the built-in dict class.

It enables the standard dict API to operate on nested dictionnaries
and cut accross list item by using dot-separated string keys.
It enables the standard dict API to operate on nested dictionaries
and cut across list item by using dot-separated string keys.

ex:
query = {...} # Any dict structure
Expand Down Expand Up @@ -116,11 +118,12 @@ def __contains__(self, path: str) -> bool:
return False

try:
item[last_key]
return True
_ = item[last_key]
except (KeyError, IndexError):
return False

return True

def __delitem__(self, path: str) -> None:
*keys, last_key = split_path(path, self.sep)
item = traverse(data=self.data, keys=keys, original_path=path)
Expand Down