Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Dict Dispatcher
class Renderer:
def __init__(self, entity):
self._entity = entity
def _expression(self):
return (type(self._entity))
_dispatch_table = {}
def __call__(self, *args, **kw):
return self.__class__._dispatch_table[self._expression()](self)
class IntRenderer(Renderer):
def _render_entity(self):
return 'INTEGER {}'.format(self._entity)
Renderer._dispatch_table[int] = _render_entity
class FloatRenderer(Renderer):
_type = float
def _render_entity(self):
return 'FLOAT {}'.format(self._entity)
Renderer._dispatch_table[float] = _render_entity
class CompositeRenderer(
IntRenderer,
FloatRenderer,
):
pass
if __name__ == '__main__':
numbers = [10, 4.1, 91.1, 1000]
for number in numbers:
renderer = CompositeRenderer(number)
print(renderer())
'''
OUTPUT:
INTEGER 10
FLOAT 4.1
FLOAT 91.1
INTEGER 1000
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment