]> code.delx.au - monosys/commitdiff
String interpolation awesomeness
authorJames Bunton <jamesbunton@fastmail.fm>
Thu, 9 Oct 2008 07:35:52 +0000 (18:35 +1100)
committerJames Bunton <jamesbunton@fastmail.fm>
Thu, 9 Oct 2008 07:35:52 +0000 (18:35 +1100)
python/stringinterpolate.py [new file with mode: 0644]
python/test_stringinterpolate.py [new file with mode: 0755]

diff --git a/python/stringinterpolate.py b/python/stringinterpolate.py
new file mode 100644 (file)
index 0000000..a55dfbd
--- /dev/null
@@ -0,0 +1,40 @@
+#!/usr/bin/env python
+
+__all__ = ["string_interpolate"]
+
+def string_interpolate(format, data):
+       fakeData = KeyDetect()
+       format % fakeData
+       keys = fakeData.keys
+
+       for d in combinations(data, keys):
+               yield format % d
+
+def myiter(obj):
+       if isinstance(obj, basestring):
+               return [obj]
+       else:
+               return obj
+
+def combinations(data, keys):
+       key = keys[0]
+       keys = keys[1:]
+
+       if len(keys) == 0:
+               for val in myiter(data[key]):
+                       yield {key: val}
+
+       else:
+               for val in myiter(data[key]):
+                       for d in combinations(data, keys):
+                               d[key] = val
+                               yield d
+
+
+class KeyDetect(object):
+       def __init__(self):
+               self.keys = []
+       def __getitem__(self, key):
+               self.keys.append(key)
+               return ""
+
diff --git a/python/test_stringinterpolate.py b/python/test_stringinterpolate.py
new file mode 100755 (executable)
index 0000000..dc9d001
--- /dev/null
@@ -0,0 +1,31 @@
+#!/usr/bin/env python
+
+import unittest
+
+from stringinterpolate import string_interpolate
+
+class TestInterpolate(unittest.TestCase):
+       def test1(self):
+               format = "%(a)s %(b)s"
+               data = {"a": "hello", "b": "world"}
+               result = list(string_interpolate(format, data))
+               expected = ["hello world"]
+               self.assertEquals(result, expected)
+       
+       def test2(self):
+               format = "%(a)s %(b)s"
+               data = {"a": ["hello", "hello2"], "b": ["world", "world2"]}
+               result = list(string_interpolate(format, data))
+               expected = ["hello world", "hello world2", "hello2 world", "hello2 world2"]
+               self.assertEquals(result, expected)
+       
+       def test3(self):
+               format = "%(a)s %(b)s"
+               data = {"a": ["hello", "hello2"], "b": "world"}
+               result = list(string_interpolate(format, data))
+               expected = ["hello world", "hello2 world"]
+               self.assertEquals(result, expected)
+
+if __name__ == "__main__":
+       unittest.main()
+