Videos
Rather than match type(v), match v directly:
values = [
1,
"hello",
True,
]
for v in values:
match v:
case str():
print("It is a string!")
case bool():
print("It is a boolean!")
case int():
print("It is an integer!")
case _:
print(f"It is a {type(v)}!")
Note that I've swapped the order of bool() and int() here, so that True being an instance of int doesn't cause issues.
This is a class pattern match.
You can match directly against the type of v, but you need a value pattern to refer to the types to match, as a "dotless" name is a capture pattern that matches any value. For example,
import builtins
values = [
1,
"hello",
True
]
# Caveat: this will continue to work even if someone
# rebinds the built-in, but not, for example, if builtins.str
# itself is rebound.
for v in values:
match type(v):
case builtins.str:
print("It is a string!")
case builtins.int:
print("It is an integer!")
case builtins.bool:
print("It is a boolean!")
case _:
print(f"It is a {type(v)}!")
Note that a value pattern must be a dotted name; it's not an arbitrary expression that can evaluate to a specific value.
(Whether you really want to match against the actual type of a value, or really want to determine if a value is an instance of a given type, is another matter. In the latter case, an if-elif statement is needed.
if isinstance(v, bool):
print("It is a boolean!")
elif isinstance(v, int):
print("It is an int!")
elif isinstance(v, str):
print("It is a string!")
else:
print(f"It is a {type(v)}!")
There is no pattern that lets you use the result of calling isinstance as the case to match against.
)