From 7ef3b40f25d464a20b8205ee1f49e98c19970424 Mon Sep 17 00:00:00 2001 From: Shroominic Date: Fri, 15 Dec 2023 12:16:17 +0100 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Refactor=20with=20pattern=20matchin?= =?UTF-8?q?g?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- examples/union_types.py | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/examples/union_types.py b/examples/union_types.py index fa5e472..5c16b5b 100644 --- a/examples/union_types.py +++ b/examples/union_types.py @@ -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}")