Providing a shorthand match case statement

Since the Structural Pattern Matching released I’ve been using it a lot,
one thing that I realized is that sometimes - I just wan’t to check if a single object “matches” a patten, something like this:

if response.status != 200 and response.get('data') and response['data'].get('error') == 'BadFormat':
    raise Exception()

changed to:

if response.status != 200:
    match response:
        case {'data': {'error': 'BadFormat'}}:
            raise Exception()

I think it would be really nice to provide a match keyword - kind of like the is keyword that will return a boolean - so this would be possible:

if response.status != 200 and response match {'error': 'BadFormat'}:
    raise Exception()

I wouldn’t push for such a change.
This is nothing more than syntactic sugar that can make it difficult to understand code.

Although the plus is that it will speed up writing programs.

How often would you use it?
More often, one match would probably not be enough (I think), for example:

if response.code != 200:
        match response:
            case {'data': {'error': 'BadFormat'}}:
                raise FormatError()
            case {'data': {'error': 'AuthFailed'}}:
                raise AuthError()

Or something like this:

if response.code != 200:
    match response:
            case {'data': {'error': error_message}}:
                raise Exception(error_message)

As are decorators, and look how useful they’ve become. I don’t have an opinion on the proposed change, but just because it’s only syntactic sugar shouldn’t disqualify it.

1 Like

Rust has this in the form of if let:

https://doc.rust-lang.org/book/ch06-03-if-let.html

I have found it extremely useful in my Rust adventures.

2 Likes

There was previously a thread that proposed using the walrus operator for if let: Mailman 3 Extrapolating PEP 634: The walrus was waiting for patmat all along - Python-ideas - python.org

The proposed syntax was

if [x, y, *z] := my_list:
    ...

meaning

match my_list:
    case [x, y, *z]:
        ...
3 Likes

The OP’s example would also normally, IMO, be written in a shorter form even without an “inline” match keyword, where the if response.status != 200 is made part of the “case” line as a guard rather than nesting the match block.

1 Like

I agree, decorators are a good example of syntactic sugar.