Skip to content
New issue

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

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

Already on GitHub? # to your account

support nested key get/set #144

Open
wants to merge 1 commit 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
28 changes: 28 additions & 0 deletions addict/addict.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,34 @@ def __setattr__(self, name, value):
else:
self[name] = value

def __getitem__(self, key):
if '.' in key:
# foo.bar
first, rest = key.split('.', 1)
if first.endswith(']'):
# foo[0].bar
first = first[:-1]
first, index_or_slice = first.split('[', 1)
if ':' in index_or_slice:
# slice
slice_param = [int(i) for i in index_or_slice.split(':')]
return super().__getitem__(first)[slice(*slice_param)][rest]
else:
# index
return super().__getitem__(first)[int(index_or_slice)][rest]
else:
return super().__getitem__(first)[rest]
elif key.endswith(']'):
key = key[:-1]
first, index_or_slice = key.split('[', 1)
if ':' in index_or_slice:
slice_param = [int(i) for i in index_or_slice.split(':')]
return super().__getitem__(first)[slice(*slice_param)]
else:
return super().__getitem__(first)[int(index_or_slice)]
else:
return super().__getitem__(key)

def __setitem__(self, name, value):
isFrozen = (hasattr(self, '__frozen') and
object.__getattribute__(self, '__frozen'))
Expand Down