It looks like the error messages should be improved. And watch out for
the gotcha!
First, here is the gotcha to watch out for. Matching on a type like this
appears to work.
match 'this is a string':
case str:
print("matched!")
prints âmatched!â as you expect. But what weâve actually done is
not match on the type str
, but matched the pattern âstrâ, which
represents a name. So it binds the matched values to the pattern, and we
get:
print(str)
# prints 'this is a string', not <class 'str'>
Gotcha!
So run del str
to get rid of that pesky variable shadowing the
built-in str type, and letâs match it properly.
del str
match 'this is a string':
case str():
print("matched!")
When matching against a type, you need parentheses after the type,
otherwise youâre just matching against a name, which is equivalent to
doing str = 'this is a string'
.
Now we can improve it by matching against the type and binding to a name
in the same test, which then lets us refer to the name that we used:
match 'this is a string':
case str(s):
print(f"matched the string {s!r}")
We can add a guard clause:
match 'this is a string':
case str(s) if s.islower():
print(f"matched the lowercase string {s!r}")
Remember, matchâŚcase is not like a switch statement. Its a disguised
assignment!