Skip to content

Instantly share code, notes, and snippets.

@gauthamchettiar
Created June 7, 2025 14:30
Show Gist options
  • Save gauthamchettiar/faf58bcb0dbdb81f10764c389145d4f1 to your computer and use it in GitHub Desktop.
Save gauthamchettiar/faf58bcb0dbdb81f10764c389145d4f1 to your computer and use it in GitHub Desktop.
python type declaration : event as dict
# dict, naive validation handling
item_event = {"type": "ITEM", "action": "EQUIP", "data": {"item": "SHORT_SWORD", "at": "LEFT_HAND", "on": "SWORDMASTER_1"}}
stat_event = { "type": "STAT", "action": "STAT_CHANGE", "data": { "stat": "EXPERIENCE", "change": { "from": 10, "to": 11 }, "on":"SWORDMASTER_1"}}
action_event = {"type": "ACTION", "action": "ATTACK", "data": {"from": "SWORDMASTER_1", "to": "ENEMY_1", "type": "SLASH" }}
def validate_event(event):
if not isinstance(event, dict):
raise TypeError("Event must be a dictionary.")
if "type" not in event or "action" not in event or "data" not in event:
raise ValueError("Event must contain 'type', 'action', and 'data' keys.")
if not isinstance(event["data"], dict):
raise TypeError("Event data must be a dictionary.")
match event["type"]:
case "ITEM":
if event["action"] == "EQUIP":
if not all(key in event["data"] for key in ["item", "at", "on"]):
raise ValueError("ITEM EQUIP event must contain 'item', 'at', and 'on' keys.")
else:
raise ValueError(f"Unsupported ITEM action: {event['action']}")
case "STAT":
if event["action"] == "STAT_CHANGE":
if not all(key in event["data"] for key in ["stat", "change", "on"]):
raise ValueError("STAT CHANGE event must contain 'stat', 'change', and 'on' keys.")
if not all(key in event["data"]["change"] for key in ["from", "to"]):
raise ValueError("STAT CHANGE change must contain 'from' and 'to' keys.")
else:
raise ValueError(f"Unsupported STAT action: {event['action']}")
case "ACTION":
if event["action"] == "ATTACK":
if not all(key in event["data"] for key in ["from", "to", "type"]):
raise ValueError("ACTION ATTACK event must contain 'from', 'to', and 'type' keys.")
else:
raise ValueError(f"Unsupported ACTION action: {event['action']}")
case _:
raise ValueError(f"Unsupported event type: {event['type']}")
def handle_event(event):
validate_event(event)
match event["type"]:
case "ITEM":
# Handle item event
pass
case "STAT":
# Handle stat event
pass
case "ACTION":
# Handle action event
pass
case _:
raise ValueError(f"Unsupported event type: {event['type']}")
if __name__ == "__main__":
try:
handle_event(item_event)
handle_event(stat_event)
handle_event(action_event)
print("All events processed successfully.")
except (TypeError, ValueError) as e:
print(f"Error processing event: {e}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment