Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor if-else Statements to match-case for Improved Readability and Maintainability in Python 3.10+ #453

Open
2 tasks done
Anselmoo opened this issue Feb 10, 2025 · 0 comments
Labels
enhancement New feature or request

Comments

@Anselmoo
Copy link

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

  1. 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.
  2. 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.
  3. 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.
@Anselmoo Anselmoo added the enhancement New feature or request label Feb 10, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant