PYTHON   43

default switch

Guest on 16th June 2022 01:41:07 AM

  1. #!/usr/bin/env python3
  2. # This switch statements supports default cases aswell
  3. class switch():
  4.     def __init__(self, key):
  5.         self.key = key
  6.         self.matchFound = False
  7.         self.defaultCase = None
  8.     def __enter__(self):
  9.         return self.case
  10.     def __exit__(self, exc_type, exc_val, exc_tb):
  11.         if not self.matchFound and self.defaultCase:
  12.             self.defaultCase()
  13.     def case(self, key = None):
  14.         def decorator(func):
  15.             if self.key == key:
  16.                 func()
  17.                 self.matchFound = True
  18.             elif key == None:
  19.                 self.defaultCase = func
  20.             return func
  21.         return decorator
  22.  
  23. for key in range(1, 101):
  24.     with switch(key % 15) as case:
  25.         @case(5)
  26.         @case(10)
  27.         def five():
  28.             print("Buzz")
  29.         @case(3)
  30.         @case(6)
  31.         @case(9)
  32.         @case(12)
  33.         def three():
  34.             print("Fizz")
  35.         @case(0)
  36.         def both():
  37.             print("Fizzuzz")
  38.         @case()
  39.         def default():
  40.             print(key)

Raw Paste


Login or Register to edit or fork this paste. It's free.