Python 3.10: match-case syntax for catching exceptions

If you know that random_number is a number there’s not much point in using pattern matching. Think of it this way, what you’re actually testing is that:

    match random_number:
        case random_number if random_number < 0:
            print("... this is something that is comparable to an int")
        case _:
            print("... or anything else")

I am generally very concerned about cylomatic complexity of my code. The match-case syntax is trying to alleviate complexity (that’s the general idea behind this new syntax), but I think that in situations where the match-case syntax tends to make the code a little bit harder to understand, one should just use the if-elif-else ladder. Although the match-case syntax is faster than the if-elif-else ladder (as I read somewhere, can’t remember where exactly), I am not going to convert every if-elif-else I have in my codebase to the match-case syntax. It’s a new toy, but it just so happens that you’re not really benefiting by playing everywhere with it.

Yes, @layday, you’re absolutely right. I was too excited about this new match-case syntax that I just wanted to use it everywhere I have an if statement in my codebase. And as I wanted to do that, I have learned a great deal about this new syntax. I have come to the conclusion that the syntax is not so exciting as I thought it would be. Basically, it’s just sintactic sugar for if-elif-else. It’s cool, but it’s not something that should replace all if-elif-else ladders in everyone’s codebases.

Now I know that a simple if random_number < 0 is good enough.

The PEP titles “Structural Pattern Matching:…” are a strong hint that the match statement is for matching structures rather than values. Strict value matching like if n > 0 ... elif n == 0 ... else # n < 0 ... is still best done with if. If one wants to do a mix of structure and value matching for the same target, then match and case, some with if guards, may be best. This is most likely if the target can be of more than one type, such as a number or sequence.

1 Like