@andymitchhank/

class-based-switch

Python

No description

fork
loading
Files
  • main.py
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Switch(object):

  def __init__(self, default):
    self.switches = {}
    self.default = default

  def get(self, name):
    return self.switches.get(name, self.default)   

  def run(self, name, *args, **kwargs):
    func = self.get(name)
    return func(*args, **kwargs)

  def on(self, name, value):
    self.switches[name] = value


if __name__ == '__main__':
  def default():
    return 'default'

  switch = Switch(default)
  
  def walk():
    return 'walking'

  switch.on('walk', walk)
  switch.on('skip', lambda: 'skipping')

  print(switch.run('walk'))
  print(switch.run('skip'))
  print(switch.run('not-an-action'))