Skip to content

Commit

Permalink
Merge pull request #10 from shakefu/namespace_key_access
Browse files Browse the repository at this point in the history
Namespace key access
  • Loading branch information
shakefu committed Apr 12, 2018
2 parents ad71a44 + bc96a66 commit bd3fe76
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
11 changes: 11 additions & 0 deletions pytool/lang.py
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,10 @@ class Namespace(object):
[[1, 2], 3]
>>> b.foo
[[9, 2], 3]
>>> # You can access keys using dict-like syntax, which is useful
>>> myns.foo.bar = True
>>> myns['foo'].bar
True
Namespaces are useful!
Expand All @@ -394,6 +398,10 @@ class Namespace(object):
Added deepcopy capability to Namespaces.
.. versionadded:: 3.8.0
Added dict-like access capability to Namespaces.
"""
def __init__(self, obj=None):
if obj is not None:
Expand All @@ -407,6 +415,9 @@ def __getattribute__(self, name):
value = value.__get__(self, self.__class__)
return value

# Allow for dict-like key access
__getitem__ = __getattribute__

def __getattr__(self, name):
# Allow implicit nested namespaces by attribute access
new_space = Namespace()
Expand Down
18 changes: 18 additions & 0 deletions test/test_lang.py
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,24 @@ def test_namespaces_reject_top_level_lists():
pytool.lang.Namespace(obj)


def test_namespaces_allow_key_access():
obj = {'foo': 1, 'bar': 2}
ns = pytool.lang.Namespace(obj)
eq_(ns['foo'], 1)


def test_namespaces_allow_key_access_for_reserved_words():
obj = {'foo': 1, 'bar': 2, 'in': 3}
ns = pytool.lang.Namespace(obj)
eq_(ns['in'], 3)


def test_namespaces_allow_key_access_for_nested_reserved_words():
obj = {'foo': {'in': {'bar': 1}}}
ns = pytool.lang.Namespace(obj)
eq_(ns.foo['in'].bar, 1)


def test_hashed_singleton_no_args():
t = HashedSingleton()
ok_(t is HashedSingleton())
Expand Down

0 comments on commit bd3fe76

Please sign in to comment.