1. Ronny Pfannschmidt
  2. pida-patches

Source

pida-patches / symbols-util

# HG changeset patch
# Parent b51f85401eb94624b0ae37ec36c28097fdcbceb5
create pida.utils.symbol as collection of ordered string constants/enums

diff --git a/pida/utils/symbols.py b/pida/utils/symbols.py
new file mode 100644
--- /dev/null
+++ b/pida/utils/symbols.py
@@ -0,0 +1,31 @@
+
+
+class Symbols(object):
+
+    def __init__(self, name, items):
+        self.items = {}
+        self.name = name
+        for index, value in enumerate(items):
+            if not value.islower():
+                raise ValueError('%s is not lower')
+            self.items[index] = value
+            self.items[value] = index
+            setattr(self, value.upper(), value)
+
+    def key(self, item):
+        """
+        :param str item: one of the symbols
+
+        key function for sorting a list of symbols
+        everything str thats not in this symbol bag gets sorted last
+        """
+        return self.items.get(item.lower(), len(self.items))
+
+    def __contains__(self, key):
+        return key.lower() in self.items
+
+    def __getitem__(self, item):
+        return self.items[item]
+
+    def __iter__(self):
+        raise TypeError("a bag of symbols is not iterable")
diff --git a/tests/utils/test_symbols.py b/tests/utils/test_symbols.py
new file mode 100644
--- /dev/null
+++ b/tests/utils/test_symbols.py
@@ -0,0 +1,35 @@
+from pida.utils.symbols import Symbols
+from py.test import raises
+
+
+def pytest_funcarg__table(request):
+    return Symbols('test', 'ab')
+
+
+def test_attrs(table):
+    assert table.A == 'a'
+    assert table.B == 'b'
+
+def test_content(table):
+    assert table['a'] == 0
+    assert table['b'] == 1
+    assert table[0] == 'a'
+    assert table[1] == 'b'
+
+def test_needs_lower():
+    raises(ValueError, Symbols, 'name', ['Foo'])
+
+def test_contains(table):
+    assert 'a' in table
+    assert 'A' in table
+
+def test_order():
+    t = Symbols('test', 'ba')
+    l = ['c', 'a', 'b']
+    l.sort(key=t.key)
+    #XXX: None sorts before anything else
+    assert l == ['b', 'a', 'c']
+
+def test_not_iterable(table):
+    with raises(TypeError):
+        list(table)