Skip to content

Commit

Permalink
lang: Add Keyspace object.
Browse files Browse the repository at this point in the history
  • Loading branch information
shakefu committed Oct 23, 2020
1 parent 68362f1 commit c9fe933
Show file tree
Hide file tree
Showing 2 changed files with 148 additions and 6 deletions.
73 changes: 67 additions & 6 deletions pytool/lang.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
]


VALID_NAME = re.compile('^[a-zA-Z0-9_.]+$')


def get_name(frame):
Expand Down Expand Up @@ -424,6 +423,8 @@ class Namespace(object):
Added traversal by key/index arrays for nested Namespaces and lists
"""
_VALID_NAME = re.compile('^[a-zA-Z0-9_.]+$')

def __init__(self, obj=None):
if obj is not None:
# Populate the namespace from the give dictionary
Expand All @@ -447,7 +448,7 @@ def __getitem__(self, item):

def __getattr__(self, name):
# Allow implicit nested namespaces by attribute access
new_space = Namespace()
new_space = type(self)()
setattr(self, name, new_space)
return new_space

Expand Down Expand Up @@ -528,6 +529,43 @@ def as_dict(self, base_name=None):
value[i] = value[i].as_dict()
return space

def for_json(self, base_name=None):
""" Return the current namespace as a JSON suitable nested dictionary.
:param str base_name: Base namespace (optional)
This is compatible with the :module:`simplejson` `for_json`
behavior flag to recursively encode objects.
Example::
import simplejson
json_str = simplejson.dumps(my_namespace, for_json=True)
"""
target = {}
obj = target if not base_name else {base_name: target}

for key in self.__dict__.keys():
value = getattr(self, key)
target[key] = value

if isinstance(value, Namespace):
value = value.for_json()
target[key] = value
continue

if isinstance(value, list):
value = copy.copy(value)
target[key] = value

for i in range(len(value)):
if isinstance(value[i], Namespace):
value[i] = value[i].for_json()

return obj

def from_dict(self, obj):
""" Populate this Namespace from the given *obj* dictionary.
Expand All @@ -544,7 +582,7 @@ def from_dict(self, obj):
def _coerce_value(value):
""" Helps coerce values to Namespaces recursively. """
if isinstance(value, dict):
return Namespace(value)
return type(self)(value)
elif isinstance(value, list):
# We have to copy the list so we can modify in place without
# breaking things
Expand All @@ -554,12 +592,12 @@ def _coerce_value(value):
return value

for key, value in obj.items():
assert VALID_NAME.match(key), "Invalid name: {!r}".format(key)
assert self._VALID_NAME.match(key), "Invalid name: {!r}".format(key)
value = _coerce_value(value)
setattr(self, key, value)

def __repr__(self):
return "<Namespace({})>".format(self.as_dict())
return "<{}({})>".format(type(self).__name__, self.as_dict())

def copy(self, *args, **kwargs):
""" Return a copy of a Namespace by writing it to a dict and then
Expand All @@ -568,7 +606,7 @@ def copy(self, *args, **kwargs):
Arguments to this method are ignored.
"""
return Namespace(self.as_dict())
return type(self)(self.as_dict())

# Aliases for the stdlib copy module
__copy__ = copy
Expand Down Expand Up @@ -610,6 +648,29 @@ def traverse(self, path):
return ns


class Keyspace(Namespace):
"""
Keyspace object which extends Namespaces by allowing item assignment and
arbitrary key names instead of just python attribute compatible names.
Example::
# This would be an error with a Namespace
my_ns['foobar'] = True
# This works with a Keyspace
my_ns.foo['foobar'].bar['you'] = True
"""
_VALID_NAME = re.compile('.*')

def __init__(self, obj=None):
super().__init__(obj)

def __setitem__(self, key, value):
self.__dict__[key] = value


def _split_keys(obj):
"""
Return a generator that yields 2-tuples of lists representing dot-notation
Expand Down
81 changes: 81 additions & 0 deletions test/test_lang.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import inspect

import pytool
import simplejson
from .util import eq_, ok_, raises


Expand Down Expand Up @@ -378,6 +379,86 @@ def test_namespace_can_merge_dict_manually():
eq_(ns.foo.fnord, 0)


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


def test_namespace_for_json_nested():
obj = {'foo': {'bar': 1}}
ns = pytool.lang.Namespace(obj)
eq_(ns.for_json(), obj)
eq_(ns.as_dict(), {'foo.bar': 1})


def test_namespace_for_json_base_name():
obj = {'foo': {'bar': 1}}
ns = pytool.lang.Namespace(obj)
eq_(ns.for_json('base'), {'base': obj})


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


def test_namspace_for_json_simplejson_encode():
obj = {'foo': {'bar': 1}}
ns = pytool.lang.Namespace(obj)
eq_(simplejson.dumps(ns, for_json=True), '{"foo": {"bar": 1}}')


def test_keyspace_allows_item_assignment():
ks = pytool.lang.Keyspace()
ks['foo'] = 1
ks['key-name'] = 2
eq_(ks.as_dict(), {'foo': 1, 'key-name': 2})


def test_keyspace_create_keyspace():
ks = pytool.lang.Keyspace()
ks.foo.bar = 1
eq_(type(ks.foo), pytool.lang.Keyspace)


def test_keyspace_allows_getitem_traversal():
ks = pytool.lang.Keyspace()
ks['foo'].bar = 1
eq_(ks.as_dict(), {'foo.bar': 1})


def test_keyspace_allows_getitem_traversal_with_nonattribute_names():
ks = pytool.lang.Keyspace()
ks['key-name'].bar = 1
eq_(ks.as_dict(), {'key-name.bar': 1})


def test_keyspace_allows_getitem_traversal_with_nonattribute_names_deep():
ks = pytool.lang.Keyspace()
ks.foo['key-name'].bar = 1
eq_(ks.as_dict(), {'foo.key-name.bar': 1})


def test_keyspace_allows_nested_item_assignment():
ks = pytool.lang.Keyspace()
ks.foo['bar'] = 1
eq_(ks.as_dict(), {'foo.bar': 1})


def test_keyspace_copy_works():
ks = pytool.lang.Keyspace()
ks.foo['key-name'].bar = 1
ks2 = copy.copy(ks)
eq_(ks.as_dict(), ks2.as_dict())


def test_keyspace_reprs_accurately_when_empty():
ns = pytool.lang.Keyspace()
eq_(repr(ns), '<Keyspace({})>')


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

0 comments on commit c9fe933

Please sign in to comment.