Advertisement
Guest User

Untitled

a guest
Sep 17th, 2019
202
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.29 KB | None | 0 0
  1. #### Some Python code
  2.  
  3. from dataclasses import dataclass
  4. from enum import Enum
  5. from typing import Union
  6.  
  7.  
  8. class ButtonType(Enum):
  9.     color_sel = 1
  10.     room_sel = 2
  11.  
  12. class HSV(Enum):
  13.     h = 1
  14.     s = 2
  15.     v = 3
  16.  
  17. # [1] Opaque payload
  18.  
  19. @dataclass
  20. class HSVColorPayload:
  21.     type: HSV
  22.     value: int
  23.  
  24. @dataclass
  25. class RoomPayload:
  26.     room_no: int  # Enum in actual life
  27.  
  28. @dataclass
  29. class ButtonEvent:
  30.     btype: ButtonType
  31.     payload: Union[HSVColorPayload, RoomPayload]
  32.  
  33. def do_color_sel(p: HSVColorPayload): pass
  34. def do_color_sel(p: RoomPayload): pass
  35.  
  36. def process_button_event(e: ButtonEvent) -> None:
  37.     handlers = {
  38.         ButtonType.color_sel: do_color_sel,
  39.         ButtonType.room_sel: do_room_self,
  40.     }
  41.     handler = handler[e.btype]
  42.     handler(e.payload)
  43.  
  44. # [1] Subclassing
  45.  
  46. @dataclass
  47. class ButtonEvent:
  48.     btype: ButtonType
  49.  
  50. @dataclass
  51. class ColorEvent(ButtonEvent):
  52.     type: HSV
  53.     value: int
  54.  
  55. @dataclass
  56. class RoomEvent(ButtonEvent):
  57.     room_no: int
  58.  
  59. def do_color_sel(e: ColorEvent): pass
  60. def do_color_sel(e: RoomEvent): pass
  61.  
  62. def process_button_event(e: ButtonEvent) -> None:
  63.     handlers = {
  64.         ButtonType.color_sel: do_color_sel,
  65.         ButtonType.room_sel: do_room_self,
  66.     }
  67.     handler = handler[e.btype]
  68.     handler(e)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement