Advertisement
DeaD_EyE

Why not put <conditions> and <statements> into a dictionary?

Nov 24th, 2018
253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.71 KB | None | 0 0
  1. # Why not put <conditions> and <statements> into a dictionary?
  2. # Dynamic add/remove of conditions keeps code clean, flexible!
  3. # Think about it!
  4.  
  5. # https://plus.google.com/100130971560879475093/posts/aStmtjJthQV
  6.  
  7. from functools import partial
  8. import operator
  9.  
  10.  
  11. def always_true(value):
  12.     return True
  13.  
  14.  
  15. def test_conditions(mapping, value):
  16.     for op, action in mapping.items():
  17.         if op(value):
  18.             action()
  19.             break
  20.  
  21.  
  22. tests = {
  23.     partial(operator.eq, 1): partial(print, 'Equal 1'),
  24.     partial(operator.lt, 1): partial(print, 'Less than 1'),
  25.     always_true: partial(print, 'Else'),
  26.     }
  27.  
  28.  
  29. test_conditions(tests, 1)
  30. test_conditions(tests, 2)
  31. test_conditions(tests, 0)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement