SHARE
TWEET

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

DeaD_EyE Nov 24th, 2018 127 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top