-
Notifications
You must be signed in to change notification settings - Fork 88
Open
Labels
enhancementNew feature or requestNew feature or request
Description
Checklist
- I think this refactoring is useful for everyone (if it's too specific, consider a custom rule)
- I have checked there are no similar issues suggesting the same thing; at least I didnt' find anything 😄
Description
In Python >=3.10 and higher, the match
statement provides a more Pythonic way to handle multiple conditions compared to the traditional if else statement. The match statement is inspired by pattern matching found in other languages, offering a cleaner and more readable way to manage complex conditional logic.
Code Before
def http_status_code_message(code):
if code == 200:
return "OK"
elif code == 404:
return "Not Found"
elif code == 500:
return "Internal Server Error"
else:
return "Unknown Status Code"
Code After
def http_status_code_message(code):
match code:
case 200:
return "OK"
case 404:
return "Not Found"
case 500:
return "Internal Server Error"
case _:
return "Unknown Status Code"
Benefits of Using match over if else
- Readability: The match statement is more readable, especially when dealing with multiple conditions. Each case is clearly separated, making it easier to understand the logic at a glance.
- Maintainability: The structure of the match statement makes it easier to add or modify cases without affecting the rest of the code. Each case is self-contained and does not require additional elif or else blocks.
- Pattern Matching: The match statement allows for more complex pattern matching, including destructuring of data structures, which can lead to more concise and expressive code.
ruancomelli
Metadata
Metadata
Assignees
Labels
enhancementNew feature or requestNew feature or request