Skip to content

Commit

Permalink
✨ Refactor with pattern matching
Browse files Browse the repository at this point in the history
  • Loading branch information
shroominic committed Dec 15, 2023
1 parent 8cdad32 commit 7ef3b40
Showing 1 changed file with 12 additions and 11 deletions.
23 changes: 12 additions & 11 deletions examples/union_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,15 @@ def extract_list(user_input: str) -> TodoList | ShoppingList:
user_input = "I need to buy apples, oranges and bananas from whole foods"
lst = extract_list(user_input)

if isinstance(lst, ShoppingList):
print("Here is your Shopping List: ")
for item in lst.items:
print(f"{item.name}: {item.description}")
print(f"You need to go to: {lst.store}")

elif isinstance(lst, TodoList):
print("Here is your Todo List: ")
for item in lst.todos:
print(f"{item.name}: {item.description}")
print(f"Urgency: {lst.urgency}")
match lst:
case ShoppingList(items=items, store=store):
print("Here is your Shopping List: ")
for item in items:
print(f"{item.name}: {item.description}")
print(f"You need to go to: {store}")

case TodoList(todos=todos, urgency=urgency):
print("Here is your Todo List: ")
for item in todos:
print(f"{item.name}: {item.description}")
print(f"Urgency: {urgency}")

0 comments on commit 7ef3b40

Please sign in to comment.