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.
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.