- I don’t like the proposed role of the
as
keyword, deviating from the role of as
in the existing match
/case
syntax.
- I believe that a more general approach – which would make it possible to use pattern matching in expressions – could have a better chance to appear useful enough to be worth implementing.
It could be something along the lines of the following expression syntax:
SUBJECT_EXPR matches PATTERN
(without any guard part!)
The value of the entire expression would always be just True
of False
.
The semantics of the new construct would be such that this:
result = SUBJECT_EXPR matches PATTERN
…would be equivalent to this:
match SUBJECT_EXPR:
case PATTERN:
result = True
case _:
result = False
It could be used where any Boolean expression can.
Examples:
if item matches {'command': command, 'value': value}:
print(command, value)
if status matches MyStatus(code) and code >= 500: # no guard, just two expressions forming an `and` expression
print("Internal server error")
else:
... # process response
c = 0
key_to_obj = {}
row = first_row()
while row matches (key, MyObj(n=int(n)) as obj):
key_to_obj[key] = obj
c += n
row = next_row()
extracted_even_id_values = [
value
for item in generate_items()
if item matches {'id': ident, 'value': value} and not ident % 2
]
process_item(myitem, is_valid=(myitem matches {'id', _, 'value': _}))
def should_item_be_consumed(item, seen_ids):
return (item matches {'id', int(ident), 'value': str()}
and ident not in seen_ids)