summaryrefslogtreecommitdiff
path: root/templates
diff options
context:
space:
mode:
authorLars Wirzenius <liw@liw.fi>2020-09-23 09:38:38 +0300
committerLars Wirzenius <liw@liw.fi>2020-09-23 10:23:45 +0300
commit9425129a44a9a37d67fb7ad0207acbcfb5fecb1e (patch)
tree06ebf606640ca7785b7f2ab046608adeced0c805 /templates
parentb1aaf1ac8e4489a78e21c55a9f8f3d04ff70fa59 (diff)
downloadsubplot-9425129a44a9a37d67fb7ad0207acbcfb5fecb1e.tar.gz
fix(python/Context): fix Namespace.get to remember default
Problem: given a Namespace ns, if I want to have a dict field and I do `d = ns.get("foo", {})` I get a dict, but it doesn't get stored in the Namespace. So next time I use the same construct to get the dict, I get a brand new dict. Fix: Store the default value in the Namespace so the same object gets returned the next time. Also add a little debug logging and improvements to repr(Context) that helped me debug this.
Diffstat (limited to 'templates')
-rw-r--r--templates/python/context.py12
-rw-r--r--templates/python/context_tests.py9
2 files changed, 18 insertions, 3 deletions
diff --git a/templates/python/context.py b/templates/python/context.py
index f7af624..9ecae19 100644
--- a/templates/python/context.py
+++ b/templates/python/context.py
@@ -27,11 +27,12 @@ class Context:
del self._vars[key]
def __repr__(self):
- return repr(self._vars)
+ return repr({"vars": self._vars, "namespaces": self._ns})
def declare(self, name):
if name not in self._ns:
self._ns[name] = NameSpace(name)
+ logging.debug(f"Context: declared {name}")
return self._ns[name]
@@ -44,7 +45,11 @@ class NameSpace:
return dict(self._dict)
def get(self, key, default=None):
- return self._dict.get(key, default)
+ if key not in self._dict:
+ if default is None:
+ return None
+ self._dict[key] = default
+ return self._dict[key]
def __setitem__(self, key, value):
self._dict[key] = value
@@ -57,3 +62,6 @@ class NameSpace:
def __delitem__(self, key):
del self._dict[key]
+
+ def __repr__(self):
+ return repr(self._dict)
diff --git a/templates/python/context_tests.py b/templates/python/context_tests.py
index ff4e558..d878084 100644
--- a/templates/python/context_tests.py
+++ b/templates/python/context_tests.py
@@ -81,10 +81,17 @@ class ContextNamepaceTests(unittest.TestCase):
ns["bar"] = "yo"
self.assertEqual(ns.get("bar", "argh"), "yo")
- def test_gets_with_default(self):
+ def test_get_without_default_doesnt_set(self):
+ ctx = Context()
+ ns = ctx.declare("foo")
+ ns.get("bar")
+ self.assertFalse("bar" in ns)
+
+ def test_gets_with_default_sets_as_well(self):
ctx = Context()
ns = ctx.declare("foo")
self.assertEqual(ns.get("bar", "yo"), "yo")
+ self.assertEqual(ns["bar"], "yo")
def test_does_not_contain_key(self):
ctx = Context()