So the match/case terminology introduced in python 3.10 is pretty cool. In general, the code <type>(arg1=value1)
is changed to the code <type>(attr1=value1)
during a case
in a match
. This allows for some very interesting and complex capturing.
For example, we can ask “does my instance have a attr called ‘sort’, if so capture it”:
match [1,2,3]:
case list(sort=f): # this isn't a call, it is an attr-capture statement
print(f)
Since the 1st (and only) positional argument of the list-instance is the list values, you can capture those items as well:
match [1,2,3]:
case list((x,*y),sort=f): # here we are capturing the 'attr' called 'sort' as 'f'
print(x,y,f)
Likewise, you can specify the matching values instead of capturing them into variables:
g = list.sort
match [1,2,3]:
case list((1,*y),sort=g): # here we ask if the attr 'sort' is the same as 'g'
print(y)
However, I am now confused by the following:
match [1,2,3]:
case list(x,sort=list.sort): # fails to match, but why???
print(x)
I would have thought that this fails because “list.sort” means something different than to specify the function ‘sort’ of ‘list’. Maybe, “sort=list.sort” means “do I have an attr called ‘sort’ which itself is of ‘type’ ‘list’ that also has an attr called ‘sort'”. So I tried:
match [1,2,3]:
case list.sort: # also fails, why???
print('ya')
So, “list.sort” does not mean that I want type list with an attr of sort. So, then I tried:
match list.sort:
case list.sort: # does match, wait, what?
print('ya')
WHICH WORKS? So, “list.sort” during a “case” DOES mean to use the function of “sort” from the type of “list”…but then why did the “list(sort=list.sort)” fail???