Commits

jhjaggars committed 5d0a34a

Adding a few examples for using dictionaries instead of switch statements

Comments (0)

Files changed (3)

code/TableDriven/command_registration.py

+command_table = {}
+
+def command(name):
+    def _add_to_command_table(function):
+        command_table[name] = function
+        return function
+    return _add_to_command_table
+
+@command('demo')
+def demo_command():
+    print("this is the demo command...")
+
+if __name__ == "__main__":
+    try:
+        command_table['demo']()
+        command_table['not_here']()
+    except KeyError as e:
+        print("could not find demo command: ", e)
+

code/TableDriven/factory.py

+class Widget(object):
+
+    def __str__(self):
+        return self.__class__.__name__
+
+class FooWidget(Widget): pass
+class BarWidget(Widget): pass
+class BazWidget(Widget): pass
+class DefaultWidget(Widget): pass
+
+class WidgetFactory(object):
+
+    widgets = {
+            "foo": FooWidget,
+            "bar": BarWidget,
+            "baz": BazWidget
+            }
+
+    @classmethod
+    def getWidget(cls, name):
+        try:
+            return cls.widgets[name]()
+        except KeyError as e:
+            return DefaultWidget()
+
+
+if __name__ == '__main__':
+    widgetA = WidgetFactory.getWidget('foo')
+    widgetB = WidgetFactory.getWidget('unknown')
+    print( widgetA )
+    print( widgetB )

code/TableDriven/switch_function.py

+def switch( on, mapping, default=None ):
+    try:
+        return mapping[on]
+    except Keyerror as e:
+        return default
+
+foo = switch( "test", {
+        "test": "you hit test",
+        "bar": "you hit bar"
+    })
+
+print(foo)